Ruby each_with_index offset

前端 未结 10 1127
长发绾君心
长发绾君心 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-12 23:56

    This works in every ruby version:

    %W(one two three).zip(1..3).each do |value, index|
      puts value, index
    end
    

    And for a generic array:

    a.zip(1..a.length.each do |value, index|
      puts value, index
    end
    

提交回复
热议问题