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

前端 未结 16 2341
眼角桃花
眼角桃花 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:37

    Sometimes a for loop is just your best option

    if(array.count > 0)
       first= array[0]
       #... do something with the first
    
       cx = array.count -2 #so we skip the last record on a 0 based array
       for x in 1..cx
         middle = array[x]
         #... do something to the middle
       end
    
       last = array[array.count-1]
       #... do something with the last item. 
    end
    

    I know this question was answered, but this method has no side effects, and doesn't check if the 13th, 14th, 15th.. 10thousandth, 10,001th... record is the first record, or the last.

    Previous answers would have failed the assignment in any data structures class.

提交回复
热议问题