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

前端 未结 16 2268
眼角桃花
眼角桃花 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
    
    0 讨论(0)
  • 2020-12-08 00:53

    If the code for the first and last iteration has nothing in common with the code for the other iterations, you could also do:

    do_something( a.first )
    a[1..-2].each do |x|
      do_something_else( x )
    end
    do_something_else_else( a.last )
    

    If the different cases have some code in common, your way is fine.

    0 讨论(0)
  • 2020-12-08 00:53

    If you know the items in the array are unique (unlike this case), you can do this:

    a = [1,2,3,4,5]
    
    a.each_with_index do |x, i|
      if x == a.first
        print x+1
      elsif x == a.last
        print x*10
      else
        print x
      end
    end
    
    0 讨论(0)
  • 2020-12-08 00:54

    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
    
    0 讨论(0)
提交回复
热议问题