I have a variable "x" in m开发者_如何学Goy view. I need to display some code "x" number of times.
I basically want to set up a loop like this:
for i = 1 to x
do something on (i)
end
Is there a way to do this?
If you're doing this in your erb view (for Rails), be mindful of the <%
and <%=
differences. What you'd want is:
<% (1..x).each do |i| %>
Code to display using <%= stuff %> that you want to display
<% end %>
For plain Ruby, you can refer to: http://www.tutorialspoint.com/ruby/ruby_loops.htm
x.times do |i|
something(i+1)
end
for i in 0..max
puts "Value of local variable is #{i}"
end
All Ruby loops
You can perform a simple each
loop on the range from 1 to `x´:
(1..x).each do |i|
#...
end
Try Below Simple Ruby Magics :)
(1..x).each { |n| puts n }
x.times { |n| puts n }
1.upto(x) { |n| print n }
精彩评论