Home » Ruby » How to create an integer-for-loop in Ruby?

How to create an integer-for-loop in Ruby?

Posted by: admin November 30, 2017 Leave a comment

Questions:

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?

Answers:

If you’re doing this in your erb view, 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 %>

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

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

All Ruby loops

Questions:
Answers:

You can perform a simple each loop on the range from 1 to `x´:

(1..x).each do |i|
  #...
end

Questions:
Answers:

Try Below Simple Ruby Magics 🙂

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