2017-02-18 288 views
1

訪問值我有一個Calculator類,讀起來就像這樣:紅寶石:通過接口

class Calculator 
    DEFAULTS = { 
    price: 4.25, size: 10000 
    }.freeze 

    def initialize(lead) 
    @lead = lead 
    end 

    def lead_attributes 
    @lead.attributes.symbolize_keys.merge(DEFAULTS) 
    end 

    def hash # massively simplified 
    lead_attributes.tap do |h| 
     h[:total] = h[:price] * h[:size] 
    end 
    end 
end 

我的問題是hash方法總是返回從DEFAULTS值雖然具有的​​6.50:price@lead:size8000。如果我不合並DEFAULTS@lead.attributes我得到一個零錯誤:

undefined method `*' for nil:NilClass 

總之,爲什麼沒有我的屬性,當我點擊他們訪問?只有匹配的@lead屬性爲nil,我纔會加載DEFAULTS

回答

3

您可能想要使用reverse_merge(或只是合併在相反的方向),否則merge將始終覆蓋現有@lead.attributes與默認值。

更改爲lead_attributes到:

def lead_attributes 
    @lead.attributes.symbolize_keys.reverse_merge(DEFAULTS) 
end 

或者:

def lead_attributes 
    DEFAULTS.merge(@lead.attributes.symbolize_keys) 
end 
+0

上['哈希#merge'](參考到文檔http://ruby-doc.org/core/Hash .html#method-i-merge)在這裏會有所幫助。另外,在純ruby中沒有方法'Hash#symbolize_keys'。 – mudasobwa

+0

啊,非常感謝!哈哈,把頭髮扯出來。 –