2010-08-23 55 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 } 

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