区分每个元素中的第一个和最后一个元素? [英] Discriminate first and last element in each?

查看:47
本文介绍了区分每个元素中的第一个和最后一个元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

@example.each do |e|
  #do something here
end

这里我想对每个元素的第一个和最后一个元素做一些不同的事情,我应该如何实现?当然,我可以使用循环变量 i 并跟踪 i==0i==@example.size ,但这不是太愚蠢了吗?

Here I want to do something different with the first and last element in each, how should I achieve this? Certainly I can use a loop variable i and keep track if i==0 or i==@example.size but isn't that too dumb?

推荐答案

更好的方法之一是:

@example.tap do |head, *body, tail|
  head.do_head_specific_task!
  tail.do_tail_specific_task!
  body.each { |segment| segment.do_body_segment_specific_task! }
end

这篇关于区分每个元素中的第一个和最后一个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆