我总是使用计数器来检查循环中的第一项 (i==0
):
i = 0
my_array.each do |item|
if i==0
# do something with the first item
end
# common stuff
i += 1
end
是否有更优雅的方式来做到这一点(也许是一种方法)?
最佳答案
你可以这样做:
my_array.each_with_index do |item, index|
if index == 0
# do something with the first item
end
# common stuff
end
试试ideone .
关于ruby - 如何在 Ruby 循环的第一次迭代中采取不同的行动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8181390/