2009-11-26 6 views

答えて

12
ように振る舞うた Object#public_methodあなた自身を書くことができ、あなた自身を記述する必要があり

私が知っているとおり、あなたはメソッドpublic_sendが必要です:

----------------------------------------------------- Object#public_send 
    obj.public_send(symbol [, args...]) => obj 

    From Ruby 1.9.1 
------------------------------------------------------------------------ 
    Invokes the method identified by _symbol_, passing it any arguments 
    specified. Unlike send, public_send calls public methods only. 

     1.public_send(:puts, "hello") # causes NoMethodError 
+1

これはruby 1.8.7では利用できません – johannes

+0

実際には、私は信じて1.9で十分です。噂は1.9で心配していますが、__send__は心配していません。しかし、私はこれを確認していない。 –

0

私はあなたがそうしたい理由を理解していない、evalを使用することができます。

class Klass 
    private 
    def private_method(arg) 
    end 
end 

k = Klass.new 
m = "private_method" 
eval "k.#{m}('an arg')" 

NoMethodError: private method `private_method' called for #<Klass:0x128a7c0> 
    from (irb):15 
    from (irb):15 
+0

評価を本当に悪いです。 mが実際にメソッド名だけを含んでいるかどうかを事前に確認する必要があります。あなたがメソッド名のように見えるものを考えてアタッカーがあなたをだまそうとしますが、本当はそうではありません。 – johannes

3

ruby​​-1.9を使用している場合は、Object#public_sendを使用して必要な処理を実行できます。

あなたはルビー1.8.7またはそれ以前のバージョンを使用している場合は、Object#public_send

class Object 
    def public_send(name, *args) 
    unless public_methods.include?(name.to_s) 
     raise NoMethodError.new("undefined method `#{name}' for \"#{self.inspect}\":#{self.class}") 
    end 
    send(name, *args) 
    end 
end 

それとも、Object#methodだけのパブリックメソッドの

class Object 
    def public_method(name) 
    unless public_methods.include?(name.to_s) 
     raise NameError.new("undefined method `#{name}' for class `#{self.class}'") 
    end 
    method(name) 
    end 
end 
0

実際、evalは実際には私が実際にそれを行う唯一の方法は1.9と思っています。可視性についての詳細を知りたい場合Jamis BuckはRubyで実際に可視性がどのような方法であるかについてawesome articleと書いています。

Rubyの可視性の他のものと同様に、他の言語とほとんど変わりません。

0

あなたはevalsendまたはpublic_sendを避けたい、またはあなたがbetter performanceをしたい場合は、public_methodmethodを使用します。

obj.public_method('my_method_name').call

あなたはこのような引数を追加することができます。

obj.public_method('my_method_name').call('some_argument_1', 'some_argument_2')

関連する問題