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

RubyFor Loop

Ruby Problem Overview


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?

Ruby Solutions


Solution 1 - Ruby

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

Solution 2 - Ruby

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

Solution 3 - Ruby

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

All Ruby loops

Solution 4 - Ruby

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

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

Solution 5 - Ruby

Try Below Simple Ruby Magics :)

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMariamView Question on Stackoverflow
Solution 1 - RubyFareesh VijayarangamView Answer on Stackoverflow
Solution 2 - RubysawaView Answer on Stackoverflow
Solution 3 - RubyTaimoor ChangaizView Answer on Stackoverflow
Solution 4 - Rubysepp2kView Answer on Stackoverflow
Solution 5 - Rubyuser3118220View Answer on Stackoverflow