2012-12-31 68 views
0

我有這樣的代碼:最簡單的方法,從方法做一個哈希調用

class Foo 

    # (method definitions) 

    def make_hash 
    { 
     some_method: some_method, 
     some_other_method: some_other_method 
    } 
    end 

end 

我怎麼能簡化,或乾燥,make_hash?我想要類似slice或Rails的attributes.slice,但適用於常規課程的方法。

回答

2

一種方法是用默認值塊創建哈希:

def methods_hash 
    @methods_hash ||= Hash.new {|hash, key| hash[key] = self.class.instance_method(key) } 
end 

所以,每次請求的哈希的關鍵時候,它會動態加載instance_method,而不必前加載它所有。 instance_method方法返回對象,因此您可能需要.to_s.to_sym以滿足您的需求。

雖然我對這個問題很感興趣,並且很想知道你的最終目標是什麼,

+0

謝謝。爲了回答你的問題,我只想要一種序列化爲公共JSON表示的方式,其中某些公共屬性是內部方法結果,而不是屬性。 – mahemoff

+0

實際上'to_json(methods:....)'也可能實現它,儘管這是JSON格式特有的。 – mahemoff

2

這樣的事情會有所幫助。

mlist = {} 

Foo.instance_methods(false).each do |name| 
    mlist[name] = Foo.instance_method(name) 
end