2014-12-02 70 views
0

我對Ruby比較陌生,並且有一些遺留代碼需要支持。在它下面的行,我不明白:set_if_nil.call在ruby中做什麼?

set_if_nil.call(:type, @config['type_1']) 

我認爲它是類型變量設置爲到@config['type_1']價值,但爲什麼調用方法呢?另外,類中沒有類型變量。這是在傳遞一個對象的方法。這是該對象的參數嗎?

回答

1

推測set_if_nil被定義爲Proc。如果是,則call方法執行該Proc,傳入:type@config...作爲參數。

AFAIK,set_if_nil未被定義爲Ruby標準庫的一部分,因此要了解有關正在發生的事情的更多詳細信息,您必須查找其定義的位置。

0

我發現github一些類似的方法調用,它看起來像你的榜樣,一個是這樣的:

def set_if_nil(attr, value) 
    write_attribute(attr, value) if read_attribute(attr).nil? 
end 

write_attribute是active_record的一部分,它「套」的屬性值。所以,想一想:(這是不實際的有效記錄代碼,但爲了容易理解)..

class A 
    def initialize 
    @attributes = {} 
    end 

    def set_if_nil(attr, value) 
    write_attribute(attr, value) if read_attribute(attr).nil? 
    end 

    def read_attribute(attr) 
    @attributes[attr] 
    end 

    def write_attribute(attr, value) 
    @attributes[attr] = value 
    end 

    def do_some_stuff 
    set_if_nil(:type, "default-type") 
    end 
end 

a = A.new 
a.do_some_stuff 
a.read_attribute(:type) # => "default-type" 

a.write_attribute(:type, "my-type") 
a.do_some_stuff 
a.read_attribute(:type) # => "my-type" 

還有其他set_if_nil實現like this one,其行爲如出一轍:

def set_if_nil(key, value) 
    @attributes[key.to_sym] ||= value 
end 

另外,stackoverflow主要用於幫助有特定問題的人,而不是學習新的語言。如果你不明白項目代碼,可以考慮讓項目維護者而不是這裏,甚至對你來說也會更容易。