Identifying last loop when using for each

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

    Use join whenever possible.

    Most often the delimiter is the same between all elements, just join them together with the corresponding function in your language.

    Ruby example,

    puts array.join(", ")
    

    This should cover 99% of all cases, and if not split the array into head and tail.

    Ruby example,

    *head, tail = array
    head.each { |each| put "looping: " << each }
    puts "last element: " << tail 
    

提交回复
热议问题