How can I run a command five times using Ruby?

RubyRuby on-Rails-3

Ruby Problem Overview


How can I run a command five times in a row?

For example:

5 * send_sms_to("xxx");

Ruby Solutions


Solution 1 - Ruby

To run a command 5 times in a row, you can do

5.times { send_sms_to("xxx") }

For more info, see the times documentation and there's also the times section of Ruby Essentials

Solution 2 - Ruby

You can use the times method of the class Integer:

5.times do 
   send_sms_to('xxx') 
end

or a for loop

for i in 1..5 do
  send_sms_to('xxx')
end

or even a upto/downto:

1.upto(5) { send_sms_to('xxx') }

Solution 3 - Ruby

Here is an example using ranges:

(1..5).each { send_sms_to("xxx") }

Note: ranges constructed using .. run from the beginning to the end inclusively.

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
QuestiondonaldView Question on Stackoverflow
Solution 1 - RubyDaniel DiPaoloView Answer on Stackoverflow
Solution 2 - RubyAndrei AndrushkevichView Answer on Stackoverflow
Solution 3 - RubyRimianView Answer on Stackoverflow