我总是使用计数器来检查循环中的第一项(i==0
):
i = 0
my_array.each do |item|
if i==0
# do something with the first item
end
# common stuff
i += 1
end
有没有一种更优雅的方法(也许是一种方法)呢?
发布于 2011-11-18 19:09:30
您可以这样做:
my_array.each_with_index do |item, index|
if index == 0
# do something with the first item
end
# common stuff
end
在ideone上试试吧。
发布于 2011-11-18 19:28:34
正如其他人所描述的那样,使用each_with_index
可以很好地工作,但考虑到多样性的原因,这里是另一种方法。
如果您只想对第一个元素执行特定操作,而对包括第一个元素在内的所有元素执行通用操作,则可以这样做:
# do something with my_array[0] or my_array.first
my_array.each do |e|
# do the same general thing to all elements
end
但是如果你不想对第一个元素做一般的事情,你可以这样做:
# do something with my_array[0] or my_array.first
my_array.drop(1).each do |e|
# do the same general thing to all elements except the first
end
发布于 2011-11-18 19:11:01
数组有一个"each_with_index“方法,这个方法在这种情况下很方便:
my_array.each_with_index do |item, i|
item.do_something if i==0
#common stuff
end
https://stackoverflow.com/questions/8181390
复制相似问题