Ruby each_with_index offset

前端 未结 10 1114
长发绾君心
长发绾君心 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:54

    Actually, Enumerator#with_index receives offset as an optional parameter:

    [:foo, :bar, :baz].to_enum.with_index(1).each do |elem, i|
      puts "#{i}: #{elem}"
    end
    

    outputs:

    1: foo
    2: bar
    3: baz
    

    BTW, I think it is there only in 1.9.2.

提交回复
热议问题