How can I run a command five times using Ruby?
RubyRuby on-Rails-3Ruby 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.