如何在Ruby循环中的第一次迭代中采取不同的行为?

Pan*_*agi 72 ruby

我总是使用计数器来检查i==0循环中的第一个项目():

i = 0
my_array.each do |item|
  if i==0
    # do something with the first item
  end
  # common stuff
  i += 1
end
Run Code Online (Sandbox Code Playgroud)

有没有更优雅的方法来做到这一点(也许是一种方法)?

det*_*zed 72

你可以这样做:

my_array.each_with_index do |item, index|
    if index == 0
        # do something with the first item
    end
    # common stuff
end
Run Code Online (Sandbox Code Playgroud)

尝试在ideone上.


Rus*_*ell 44

使用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
Run Code Online (Sandbox Code Playgroud)

但是如果你不想用你能做的第一个元素做一般事情:

# 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
Run Code Online (Sandbox Code Playgroud)

  • 我喜欢`my_array.drop(1)`它更具说明性. (12认同)