Identifying last loop when using for each

后端 未结 25 1432
眼角桃花
眼角桃花 2020-12-08 09:59

I want to do something different with the last loop iteration when performing \'foreach\' on an object. I\'m using Ruby but the same goes for C#, Java etc.

          


        
25条回答
  •  隐瞒了意图╮
    2020-12-08 10:16

    Would it be a viable solution for your case to just take the first/last elements out of your array before doing the "general" each run?

    Like this:

    list = ['A','B','C','D']
    first = list.shift
    last = list.pop
    
    puts "First one: #{first}"
    list.each{|i|
      puts "Looping: "+i
    }
    puts "Last one: #{last}"
    

提交回复
热议问题