Ruby each_with_index offset

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

    The following is succinct, using Ruby's Enumerator class.

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

    output

    1: foo
    2: bar
    3: baz
    

    Array#each returns an enumerator, and calling Enumerator#with_index returns another enumerator, to which a block is passed.

提交回复
热议问题