Ruby/Rails 循环中的魔术第一个和最后一个指示器? [英] Magic First and Last Indicator in a Loop in Ruby/Rails?

查看:53
本文介绍了Ruby/Rails 循环中的魔术第一个和最后一个指示器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Ruby/Rails 在基本事物的糖方面做了很多很酷的事情,我认为有一个非常常见的场景,我想知道是否有人做过助手或类似的事情.

Ruby/Rails does lots of cool stuff when it comes to sugar for basic things, and I think there's a very common scenario that I was wondering if anyone has done a helper or something similar for.

   a = Array.new(5, 1)

   a.each_with_index do |x, i|
     if i == 0
       print x+1
     elsif i == (a.length - 1)
       print x*10
     else
        print x
     end
   end

请原谅丑陋,但这正是人们可能想要的......是否有一种红宝石方法可以对循环的第一个和最后一个执行某些操作?

Pardon the ugliness, but this gets at what one might want... is there a ruby way to do something to the first and last of a loop?

我认为理想情况下这将是对带参数的 Array 的扩展(数组实例、所有元素函数、第一个元素函数、最后一个元素函数)......但我愿意接受其他想法.

I think ideally this would be an extension on Array with parameters (array instance, all elements function, first elements function, last elements function)... but I'm open to other thoughts.

推荐答案

如果您愿意,您可以获取第一个和最后一个元素并对其进行不同的处理.

You could grab the first and last elements and process them differently, if you like.

first = array.shift
last = array.pop
process_first_one
array.each { |x| process_middle_bits }
process_last_one

这篇关于Ruby/Rails 循环中的魔术第一个和最后一个指示器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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