这个ruby for循环有什么问题?

时间:2014-04-20 13:36:17

标签: ruby for-loop control-flow

for current_iteration_number in 99..1 do      
   puts "#{current_iteration_number} of beer on the wall. 
   #{current_iteration_number} of beer. Take one down, 
   pass it around #{current_iteration_number} of beer."    
end

3 个答案:

答案 0 :(得分:2)

对于反向范围,Ruby并不像那样工作。

您应该使用其他一些方法。

例如:

99.downto(1).each do |current_iteration_number|
    puts "#{current_iteration_number} of beer on the wall. #{current_iteration_number} of beer. Take one down, pass it around #{current_iteration_number} of beer."
end

答案 1 :(得分:2)

而不是:

for current_iteration_number in 99..1 do

你可以这样做:

for current_iteration_number in 99.downto(1) do

答案 2 :(得分:0)

你也可以这样做

a= 99..1

(a.first).downto(a.last).each do |current_iteration_number|
puts "#{current_iteration_number} of beer on the wall. 
   #{current_iteration_number} of beer. Take one down, 
   pass it around #{current_iteration_number} of beer.
end