在 Ruby 中需要遍历数组元素或者对象属性时,可以使用 each 或者 each_with_index。
each例子:
fruits = ["apple", "banana", "cherry"]
fruits.each do |fruit|
puts fruit
end
# 输出:
apple
banana
cherry
当你需要获取数组元素的索引值,或者对象属性的key时,你可以使用 each_with_index,例如:
fruits = ["apple", "banana", "cherry"]
fruits.each_with_index do |fruit, index|
puts "#{index}: #{fruit}"
end
# 输出:
0: apple
1: banana
2: cherry