64

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?

1
  • I am sorry to be asking such a simple question but I have reviewed the documentation, just still not sure how to run a for loop 3 times. Commented Oct 23, 2012 at 18:25

3 Answers 3

119
3.times do # do work here end 

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

Sign up to request clarification or add additional context in comments.

4 Comments

so just run a do loop around the for loop?
Yes, unless you want something different. If you try it and play with the code you will answer all\most of your questions. Just debug and print what the code is doing.
How do you retrieve the index if you need it?
@GrahamS. I know this is old but you just need to add |i| after do like so 3.times do |i|
22

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

Comments

10

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.