foo = [3, 6, 3]
for a in foo:
print a
我如何在红宝石中做到这一点?
答案 0 :(得分: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
答案 1 :(得分:4)
foo = [3, 6, 3]
foo.each do |a|
puts a
end
答案 2 :(得分:2)
foo = [1, 2, 3]
foo.each do |x|
puts x
end
答案 3 :(得分:1)
你已经有了关于“for”-loop的正确答案。但在完全你的例子中,我将使用:
puts foo
在这种情况下你也可以使用这个'puts'功能:
puts array.map { |i| ...some code...; x }
而不是
array.each { |i| ...some code...; puts x }
例如,如果您只想调用一次。