我总是使用计数器判断循环中的第一项(i==0
):
i = 0
my_array.each do |item|
if i==0
# do something with the first item
end
# common stuff
i += 1
end
有没有更优雅的方法(也许是一种方法)?
我总是使用计数器判断循环中的第一项(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码.