2011-03-20 141 views

回答

91

如果你在你的ERB鑑於這樣做,是銘記<%<%=差異。什麼你想要的是:

<% (1..x).each do |i| %> 
    Code to display using <%= stuff %> that you want to display  
<% end %> 
73
x.times do |i| 
    something(i+1) 
end 
+6

這是Rails的方式 – Willian 2014-08-27 21:05:05

+0

第一次迭代將是I = 0。按照OP的要求,本例中的'i + 1'有效地導致了基於1的迭代。 – 2017-12-04 18:37:34

7

您可以對範圍內的簡單each環從1到`X':

(1..x).each do |i| 
    #... 
end 
9
for i in 0..max 
    puts "Value of local variable is #{i}" 
end 

All Ruby loops

+0

儘管其他解決方案可行,但這是最正確的答案,因爲它使用了for循環。 – Andrew 2016-05-07 05:12:17

+0

這是在Ruby中執行FOR LOOP的更好解決方案 – 2017-06-06 21:44:37

3

試試下面簡單的Ruby魔術的:)

(1..x).each { |n| puts n } 
x.times { |n| puts n } 
1.upto(x) { |n| print n }