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?
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 ...
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With