Ruby library function to convert Enumerable to Hash

Consider this extension for Enumerable:

module Enumerable def hash_on h = {} each do |e| h[yield(e)] = e end h end end 

Used like this:

 people = [ {:name=>'fred', :age=>32}, {:name=>'barney', :age=>42}, ] people_hash = people.hash_on { |person| person[:name] } p people_hash['fred'] # => {:age=>32, :name=>"fred"} p people_hash['barney'] # => {:age=>42, :name=>"barney"} 

Is there a built-in function that already does this, or close enough to it, that this extension is not required?

+4
source share
2 answers

Enumerable.to_h converts the sequence [key, value] to Hash so you can:

 people.map {|p| [p[:name], p]}.to_h 

If you have multiple values ​​mapped to the same key, this saves the latter.

+4
source
 [ {:name=>'fred', :age=>32}, {:name=>'barney', :age=>42}, ].group_by { |person| person[:name] } => {"fred"=>[{:name=>"fred", :age=>32}], "barney"=>[{:name=>"barney", :age=>42}]} 

Array-shaped keys have the ability to have multiple Freds or Barneys, but you can use .map to restore if you really need to.

+5
source

Source: https://habr.com/ru/post/1337176/


All Articles