Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby library function to transform Enumerable to Hash

Consider this extension to Enumerable:

module Enumerable

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

end

It is used like so:

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 which already does this, or close enough to it that this extension is not needed?

like image 615
Wayne Conrad Avatar asked Jan 26 '11 17:01

Wayne Conrad


2 Answers

Enumerable.to_h converts a sequence of [key, value]s into a Hash so you can do:

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

If you have multiple values mapped to the same key this keeps the last one.

like image 173
Lee Avatar answered Nov 15 '22 11:11

Lee


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

=> {"fred"=>[{:name=>"fred", :age=>32}],
   "barney"=>[{:name=>"barney", :age=>42}]}

Keys are in form of arrays to have a possibility to have a several Freds or Barneys, but you can use .map to reconstruct if you really need.

like image 24
Nakilon Avatar answered Nov 15 '22 10:11

Nakilon