开发者

Ruby library function to transform Enumerable to Hash

开发者 https://www.devze.com 2023-02-06 17:25 出处:网络
Consider this extension to Enumerable: module Enumerable def hash_on h = {} each do |e| h[yi开发者_如何学Celd(e)] = e

Consider this extension to Enumerable:

module Enumerable

  def hash_on
    h = {}
    each do |e|
      h[yi开发者_如何学Celd(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?


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.


[   {: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.

0

精彩评论

暂无评论...
验证码 换一张
取 消