Ruby each_with_index offset

前端 未结 10 1155
长发绾君心
长发绾君心 2020-12-12 23:32

Can I define the offset of the index in the each_with_index loop iterator? My straight forward attempt failed:

some_array.each_with_index{|item, index = 1| s         


        
10条回答
  •  醉话见心
    2020-12-13 00:10

    Another approach is to use map

    some_array = [:foo, :bar, :baz]
    some_array_plus_offset_index = some_array.each_with_index.map {|item, i| [item, i + 1]}
    some_array_plus_offset_index.each{|item, offset_index| some_func(item, offset_index) }
    

提交回复
热议问题