2013-01-23 34 views
1

我想從一個數組的行中構建一個哈希。我可以用下面的代碼輕鬆完成。我從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'} 

回答

5

您可以使用Hash[]

Hash[ product_features.map{|f| [f.feature_id, f.value]} ] 

您希望這更好的?

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

然後去看看this feature request並發表評論!

替代方案:

product_features.each_with_object({}){|f, h| h[f.feature_id] = f.value} 

還有group_byindex_by這可能是有用的,但值將是功能本身,而不是他們value

+0

甜!謝啦! RubyMine不喜歡這種語法,但它工作正常!是的,這種方法看起來很方便! –

1

你的代碼是一個很好的方法。另一種方法是:

def features_hash 
    product_features.inject({}) do |features_hash, feature| 
    features_hash[feature.feature_id] = feature.value 
    features_hash 
    end 
end 
+0

啊對了,謝謝!不知道我喜歡這種方式,雖然.. –

3

您可以使用index_by此:

product_features.index_by(&:id) 

這將產生相同的結果手工建造的哈希與id爲關鍵和記錄作爲值。

+0

(我喜歡這個解決方案最好,儘管這不是要求的。) –

+0

我誤讀了關於映射到'value'的問題。以散列格式獲取內容是一種非常方便的通用方法。我會看看是否可以使用這個快捷方式來提取單個值。 –

+0

我真的很喜歡這種方法,實際上我可以使用它,謝謝! –