Ruby `each_with_object` with index

前端 未结 3 1204
闹比i
闹比i 2021-02-02 07:25

I would like to do a.each_with_object with index, in a better way than this:

a = %w[a b c]
a.each.with_index.each_with_object({}) { |ar         


        
相关标签:
3条回答
  • 2021-02-02 07:47

    You could replace your last line with

    puts "i is: %d, v is %s" % arr.reverse
    

    but, as @sawa suggested, disambiguating the array's argument is the thing to do here. I just mention this as something to be stored away for another day.

    0 讨论(0)
  • 2021-02-02 07:50

    In your example .each.with_index is redundant. I found this solution:

    ['a', 'b', 'c'].each_with_object({}).with_index do |(el, acc), index|
      acc[index] = el
    end
    # => {0=>"a", 1=>"b", 2=>"c"}
    
    0 讨论(0)
  • 2021-02-02 08:09

    Instead of

    |arr, hash|
    

    you can do

    |(v, i), hash|
    
    0 讨论(0)
提交回复
热议问题