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[]:Would you like this better?
Then go and check out this feature request and comment on it!
Alternative solutions:
There is also
group_byandindex_bywhich could be helpful, but the values will be the features themselves, not theirvalue.