Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

for-loop

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?

like image 211
Mariam Avatar asked Mar 20 '11 18:03

Mariam


People also ask

How do you write a for loop in Ruby?

The simplest way to create a loop in Ruby is using the loop method. loop takes a block, which is denoted by { ... } or do ... end . A loop will execute any code within the block (again, that's just between the {} or do ...

How do you create an int in Ruby?

In Ruby, one can use get. chmop. to_i to take integer inputs from user. In this example, the class of a is Fixnum and this shows that a is an integer.

How does for loop work in Ruby?

Ruby until loop will executes the statements or code till the given condition evaluates to true. Basically it's just opposite to the while loop which executes until the given condition evaluates to false. An until statement's conditional is separated from code by the reserved word do, a newline, or a semicolon.

What does .times do in Ruby?

The times function in Ruby returns all the numbers from 0 to one less than the number itself. It iterates the given block, passing in increasing values from 0 up to the limit. If no block is given, an Enumerator is returned instead.


1 Answers

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

like image 154
Fareesh Vijayarangam Avatar answered Oct 07 '22 01:10

Fareesh Vijayarangam