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

RubyFor Loop

Ruby Problem Overview


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?

Ruby Solutions


Solution 1 - Ruby

3.times do
   # do work here
end 

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

Solution 2 - Ruby

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

Solution 3 - Ruby

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

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
QuestionTJ SherrillView Question on Stackoverflow
Solution 1 - RubySullyView Answer on Stackoverflow
Solution 2 - RubyricksView Answer on Stackoverflow
Solution 3 - RubyPlasmarobView Answer on Stackoverflow