Array to Hash Ruby

后端 未结 9 472
无人及你
无人及你 2021-01-29 17:43

Okay so here\'s the deal, I\'ve been googling for ages to find a solution to this and while there are many out there, they don\'t seem to do the job I\'m looking for.

Ba

相关标签:
9条回答
  • 2021-01-29 18:26

    Just use Hash.[] with the values in the array. For example:

    arr = [1,2,3,4]
    Hash[*arr] #=> gives {1 => 2, 3 => 4}
    
    0 讨论(0)
  • 2021-01-29 18:26

    Enumerator includes Enumerable. Since 2.1, Enumerable also has a method #to_h. That's why, we can write :-

    a = ["item 1", "item 2", "item 3", "item 4"]
    a.each_slice(2).to_h
    # => {"item 1"=>"item 2", "item 3"=>"item 4"}
    

    Because #each_slice without block gives us Enumerator, and as per the above explanation, we can call the #to_h method on the Enumerator object.

    0 讨论(0)
  • 2021-01-29 18:26
    a = ["item 1", "item 2", "item 3", "item 4"]
    Hash[ a.each_slice( 2 ).map { |e| e } ]
    

    or, if you hate Hash[ ... ]:

    a.each_slice( 2 ).each_with_object Hash.new do |(k, v), h| h[k] = v end
    

    or, if you are a lazy fan of broken functional programming:

    h = a.lazy.each_slice( 2 ).tap { |a|
      break Hash.new { |h, k| h[k] = a.find { |e, _| e == k }[1] }
    }
    #=> {}
    h["item 1"] #=> "item 2"
    h["item 3"] #=> "item 4"
    
    0 讨论(0)
提交回复
热议问题