首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在Ruby循环的第一次迭代中采取不同的行为?

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

Stack Overflow用户
提问于 2011-11-18 19:05:44
回答 7查看 33.3K关注 0票数 74

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

代码语言:javascript
复制
i = 0
my_array.each do |item|
  if i==0
    # do something with the first item
  end
  # common stuff
  i += 1
end

有没有一种更优雅的方法(也许是一种方法)呢?

EN

回答 7

Stack Overflow用户

回答已采纳

发布于 2011-11-18 19:09:30

您可以这样做:

代码语言:javascript
复制
my_array.each_with_index do |item, index|
    if index == 0
        # do something with the first item
    end
    # common stuff
end

ideone上试试吧。

票数 75
EN

Stack Overflow用户

发布于 2011-11-18 19:28:34

正如其他人所描述的那样,使用each_with_index可以很好地工作,但考虑到多样性的原因,这里是另一种方法。

如果您只想对第一个元素执行特定操作,而对包括第一个元素在内的所有元素执行通用操作,则可以这样做:

代码语言:javascript
复制
# do something with my_array[0] or my_array.first
my_array.each do |e| 
  # do the same general thing to all elements 
end

但是如果你不想对第一个元素做一般的事情,你可以这样做:

代码语言:javascript
复制
# 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
票数 47
EN

Stack Overflow用户

发布于 2011-11-18 19:11:01

数组有一个"each_with_index“方法,这个方法在这种情况下很方便:

代码语言:javascript
复制
my_array.each_with_index do |item, i|
  item.do_something if i==0
  #common stuff
end
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8181390

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档