加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Ruby库函数将Enumerable转换为Hash

发布时间:2020-12-17 03:52:10 所属栏目:百科 来源:网络整理
导读:考虑Enumerable的这个扩展: module Enumerable def hash_on h = {} each do |e| h[yield(e)] = e end h endend 它是这样使用的: people = [ {:name='fred',:age=32},{:name='barney',:age=42},]people_hash = people.hash_on { |person| person[:name] }p
考虑Enumerable的这个扩展:

module Enumerable

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

end

它是这样使用的:

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"}

是否有内置功能已经这样做,或者足够接近它不需要这个扩展?

解决方法

Enumerable.to_h将[key,value]序列转换为Hash,以便您可以执行以下操作:

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

如果您有多个值映射到同一个键,则保留最后一个.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读