对于数组[1, 2, 3, 4],
,当我处理每个元素时,如何知道我在数组的最后一个元素上。
arr = [1, 2, 3, 4]
arr.each do |a|
...
end
答案 0 :(得分:3)
arr = [1, 2, 3, 4]
l = arr.length - 1
arr.each_with_index do |a, i|
if i == l
...
else
...
end
end
答案 1 :(得分:3)
arr = [1, 2, 3, 4]
arr.each_with_index do |el, idx|
if idx == arr.length - 1
# you're on the last element
end
end