创建ruby哈希的更好方法是什么?

Mat*_*rey 1 ruby hash ruby-on-rails

我想从数据库的行数组中构建一个哈希.我可以使用下面的代码轻松完成.我从PHP来到Ruby,这就是我要做的.在Ruby(或Rails)中有更好/正确的方法吗?

def features_hash
  features_hash = {}
  product_features.each do |feature|
    features_hash[feature.feature_id] = feature.value
  end

  features_hash
end

# {1 => 'Blue', 2 => 'Medium', 3 => 'Metal'}
Run Code Online (Sandbox Code Playgroud)

Mar*_*une 5

你可以使用Hash[]:

Hash[ product_features.map{|f| [f.feature_id, f.value]}  ]
Run Code Online (Sandbox Code Playgroud)

你想要更好吗?

product_features.map{|f| [f.feature_id, f.value]}.to_h # no available (yet?)
Run Code Online (Sandbox Code Playgroud)

然后去查看此功能请求并对其进行评论!

替代方案:

product_features.each_with_object({}){|f, h| h[f.feature_id] = f.value}
Run Code Online (Sandbox Code Playgroud)

还有group_byindex_by这可能是有用的,但值将是功能本身,而不是他们value.