Identifying last loop when using for each

后端 未结 25 1484
眼角桃花
眼角桃花 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:14

    In Ruby I'd use each_with_index in this situation

    list = ['A','B','C']
    last = list.length-1
    list.each_with_index{|i,index|
      if index == last 
        puts "Last one: "+i 
      else 
        puts "Looping: "+i # if not last loop iteration
      end
    }
    

提交回复
热议问题