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

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

    I see a lot of hacks here that are pretty close, but all heavily dependent on the given iterator having a fixed size and NOT being an iterator. I'd like to also propose saving the previous element as you iterate through to know the first/last element that was iterated over.

    previous = {}
    elements.each do |element|
      unless previous.has_key?(:element)
        # will only execute the first time
      end
    
      # normal each block here
    
      previous[:element] = element
    end
    
    # the last element will be stored in previous[:element] 
    

提交回复
热议问题