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

Ruby:来自循环迭代方法的更清晰的返回

发布时间:2020-12-17 01:25:58 所属栏目:百科 来源:网络整理
导读:我发现我经常有遍历可枚举的方法,以便返回不同的可枚举或散列.这些方法几乎总是看起来像这个简单的例子: def build_hash(array) hash = {} array.each do |item| hash[ item[:id] ]= item end hash end 这种方法有效,但我经常想知道是否有更简洁的方法来执
我发现我经常有遍历可枚举的方法,以便返回不同的可枚举或散列.这些方法几乎总是看起来像这个简单的例子:

def build_hash(array)
    hash = {}
    array.each do |item|
      hash[ item[:id] ]= item
    end
    hash
  end

这种方法有效,但我经常想知道是否有更简洁的方法来执行此操作,特别是无需将循环包装在临时对象中以便返回正确.

有没有人知道改进的和/或更清洁和/或更快的方法,或者这是最好的方式吗?

解决方法

考虑到您的具体示例,以下是一些方法

arr = [{:id => 1,:name => :foo},{:id => 2,:name => :bar}]

Hash[arr.map{ |o| [o[:id],o] }]
arr.each_with_object({}){ |o,h| h[o[:id]] = o }
arr.reduce({}){ |h,o| h[o[:id]] = o; h }
arr.reduce({}){ |h,o| h.merge o[:id] => o }

# each of these return the same Hash
# {1=>{:id=>1,:name=>:foo},2=>{:id=>2,:name=>:bar}}

(编辑:李大同)

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

    推荐文章
      热点阅读