2010-08-23 41 views

回答

11
list = %w(a b c) 

# there's a for statement but nobody likes it :P 
for item in list 
    puts item 
end 

# so you use the each method with a block instead 

# one-liner block 
list.each { |item| puts item } 

# multi-line block 
list.each do |item| 
    puts item 
end 
4
foo = [3, 6, 3] 
foo.each do |a| 
    puts a 
end 
2
foo = [1, 2, 3] 
foo.each do |x| 
    puts x 
end 
1

你已经有两个关于正确答案 “为” -loop。但究竟你的榜样,我将使用:

puts foo 

您也可以在这种情况下使用该看跌期权功能:

puts array.map { |i| ...some code...; x } 

代替

array.each { |i| ...some code...; puts x } 

例如,如果你只需要拨一次即可。