Magic First and Last Indicator in a Loop in Ruby/Rails?

前端 未结 16 2266
眼角桃花
眼角桃花 2020-12-08 00:01

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 s

16条回答
  •  醉梦人生
    2020-12-08 00:52

    There's no "do this the (first|last) time" syntax in Ruby. But if you're looking for succinctness, you could do this:

    a.each_with_index do |x, i|
      print (i > 0 ? (i == a.length - 1 ? x*10 : x) : x+1)
    end
    

    The result is what you'd expect:

    irb(main):001:0> a = Array.new(5,1)
    => [1, 1, 1, 1, 1]
    irb(main):002:0> a.each_with_index do |x,i|
    irb(main):003:1*   puts (i > 0 ? (i == a.length - 1 ? x*10 : x) : x+1)
    irb(main):004:1> end
    2
    1
    1
    1
    10
    

提交回复
热议问题