I want to build a hash from an array of rows from a DB. I can easily do it with the code below. I've come to Ruby from PHP and this is how I would do it. Is there a better/proper way to do this in Ruby (or 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'}
You can use Hash[]
:
Hash[ product_features.map{|f| [f.feature_id, f.value]} ]
Would you like this better?
product_features.map{|f| [f.feature_id, f.value]}.to_h # no available (yet?)
Then go and check out this feature request and comment on it!
Alternative solutions:
product_features.each_with_object({}){|f, h| h[f.feature_id] = f.value}
There is also group_by
and index_by
which could be helpful, but the values will be the features themselves, not their value
.
You can use index_by
for this:
product_features.index_by(&:id)
This produces the same results as hand-constructing a hash with id
as the key and the records as the values.
Your code is a good way to do it. Another way is:
def features_hash
product_features.inject({}) do |features_hash, feature|
features_hash[feature.feature_id] = feature.value
features_hash
end
end
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.