2010-02-24 112 views
3

我將如何使用參數值作爲對象的實例變量名稱?Ruby - 如何使用方法參數作爲變量的名稱?

這是對象

Class MyClass  
    def initialize(ex,ey) 
     @myvar = ex 
     @myothervar = ey 
    end 
end 

我有以下方法

def test(element) 
    instanceofMyClass.element #this obviously doesnt work 
end 

我怎樣纔能有測試方法返回任一MYVAR或myothervar值取決於元件的參數。我不想寫if條件,但是我想通過元素將myvar或myother var傳遞給對象實例(如果可能的話)。

回答

4
def test(element) 
    instanceofMyClass.send(element.to_sym) 
end 

如果instanceofMyClass對元素沒有響應,您將得到缺少的方法錯誤。

+1

要明確EmFi的方法和我的區別:這個需要你有一個實例變量的讀取方法,並在我的直接訪問時通過它。 – Chuck 2010-02-24 20:27:00

+1

to_sym不需要順便說一句。發送接受字符串。 – sepp2k 2010-02-24 20:32:02

+0

完美,謝謝大家「instanceofMyClass.send(element)」做得很漂亮。由於我已經有讀者,這個似乎是最乾淨/最簡單的。 – eakkas 2010-02-24 21:52:35

3
def test(element) 
    instanceofmyclass.instance_variable_get element 
end 

test :@myvar # => ex 
test :@myothervar # => ey 
+0

我認爲這是一個很好的清潔之一。 – johannes 2010-02-25 00:54:21

+0

說實話,如果我們正在談論一個公共財產(就像EmFi的案例所假設的那樣),我會使用'send' - 這樣一來,我們就可以在覆蓋面上玩得很開心。這只是對所問問題的一般回答,通常是關於實例變量。 – Chuck 2010-02-25 02:55:39

0

我喜歡的send()簡單,但它一個壞的事情是,它可以用來訪問士兵。這個問題仍然是下面的解決方案,但至少在明確指定的情況下,讀者可以看到哪些方法將被轉發。第一個只使用委託,而第二個使用更動態的方式來即時定義方法。

require 'forwardable' 
class A 
    extend Forwardable 
    def_delegators :@myinstance, :foo, :bar 

    class B 
    def foo 
     puts 'foo called' 
    end 

    def bar 
     puts 'bar called' 
    end 

    def quux 
     puts 'quux called' 
    end 

    def bif 
     puts 'bif called' 
    end 
    end 

    def initialize 
    @myinstance = B.new 
    end 

    %i(quux bif).each do |meth| # note that only A#quux and A#bif are defined dynamically 
    define_method meth do |*args_but_we_do_not_have_any| 
     @myinstance.send(meth) 
    end 
    end 
end 

a = A.new 

a.foo 
a.bar 

a.quux 
a.bif