0

对于一个数组[1, 2, 3, 4],,当我处理每个元素时,我怎么知道我在数组的最后一个元素上。

arr = [1, 2, 3, 4]
arr.each do |a|

...

end
4

2 回答 2

3
arr = [1, 2, 3, 4]
l = arr.length - 1
arr.each_with_index do |a, i|
  if i == l
    ...
  else
    ...
  end
end
于 2012-06-27T10:36:29.650 回答
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
于 2012-06-27T10:37:42.640 回答