Ruby each_with_index offset

前端 未结 10 1037
长发绾君心
长发绾君心 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:49
    offset = 2
    some_array[offset..-1].each_with_index{|item, index| some_func(item, index+offset) }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-12 23:55

    I ran into it.

    My solution not necessary is the best, but it just worked for me.

    In the view iteration:

    just add: index + 1

    That's all for me, as I don't use any reference to those index numbers but just for show in a list.

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-13 00:04

    Ariel is right. This is the best way to handle this, and it's not that bad

    ary.each_with_index do |a, i|
      puts i + 1
      #other code
    end
    

    That is perfectly acceptable, and better than most of the solutions I've seen for this. I always thought this was what #inject was for...oh well.

    0 讨论(0)
提交回复
热议问题