[ruby] How to create an integer-for-loop in Ruby?

I have a variable "x" in my 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?

This question is related to ruby for-loop

The answer is


x.times do |i|
    something(i+1)
end

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 }

for i in 0..max
   puts "Value of local variable is #{i}"
end

All Ruby loops