Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Ruby, how can I iterate over a for loop n.times

Tags:

for-loop

ruby

I have a basic ruby loop

for video in site.posts
  video.some_parameter
endfor

I want to run this loop 2 or 3 times.

Is this possible?

like image 909
TJ Sherrill Avatar asked Oct 23 '12 17:10

TJ Sherrill


People also ask

Can you do a for loop in Ruby?

Loops are a fundamental concept in any programming language. They allow us to execute a specific action continuously as long as a specified condition is true. Ruby also offers the concept of loops that can perform similar actions.

What is the simplest way to iterate through the items of an array Ruby?

The Ruby Enumerable#each method is the most simplistic and popular way to iterate individual items in an array. It accepts two arguments: the first being an enumerable list, and the second being a block. It takes each element in the provided list and executes the block, taking the current item as a parameter.


3 Answers

3.times do
   # do work here
end 

check http://www.tutorialspoint.com/ruby/ruby_loops.htm

like image 90
Sully Avatar answered Oct 19 '22 01:10

Sully


If you need an index:

5.times do |i|
  print i, " "
end

Returns:

0 1 2 3 4

Reference: https://apidock.com/ruby/Integer/times

like image 36
ricks Avatar answered Oct 19 '22 00:10

ricks


It's bad style to use for.

3.times do
  site.posts.each do |video|
    video.some_parameter
  end
end

or if video.some_parameter is one line,

3.times do
  site.posts.each { |video| video.some_parameter }
end

see: https://github.com/bbatsov/ruby-style-guide#source-code-layout

like image 10
Plasmarob Avatar answered Oct 18 '22 23:10

Plasmarob