...ジェネリックオブジェクトのパブリックメソッドをすべて含めないでください。配列減算以外のことです。私はただドキュメントに行くことなく、オブジェクトから私が利用できるものをすぐに見直したいと思う。Rubyに、オブジェクトのパブリックメソッドを表示する方法はありますか
2
A
答えて
10
methods
、instance_methods
、public_methods
、private_methods
とprotected_methods
すべては、あなたのオブジェクトの親のメソッドが含まれているかどうかを判断するブールパラメータを受け入れます。例えば
:
ruby-1.9.2-p0 > class MyClass < Object; def my_method; return true; end; end;
ruby-1.9.2-p0 > MyClass.new.public_methods
=> [:my_method, :nil?, :===, :=~, :!~, :eql?, :hash, :<=>, :class, :singleton_class, :clone, :dup, :initialize_dup, :initialize_clone, :taint, :tainted?, :untaint, :untrust, :untrusted?, :trust, :freeze, :frozen?, :to_s, :inspect, :methods, :singleton_methods, :protected_methods, :private_methods, :public_methods, :instance_variables, :instance_variable_get, :instance_variable_set, :instance_variable_defined?, :instance_of?, :kind_of?, :is_a?, :tap, :send, :public_send, :respond_to?, :respond_to_missing?, :extend, :display, :method, :public_method, :define_singleton_method, :__id__, :object_id, :to_enum, :enum_for, :==, :equal?, :!, :!=, :instance_eval, :instance_exec, :__send__]
ruby-1.9.2-p0 > MyClass.new.public_methods(false)
=> [:my_method]
@Marnenで述べたように、(。例えばmethod_missing
で)動的に定義されたメソッドは、ここでは表示されません。これらのライブラリの唯一の賭けは、使用しているライブラリが十分に文書化されていることを期待しています。
0
Rubyがダイナミックメタプログラミングによってメソッドを偽装することができるため、パブリックメソッドが唯一の選択肢ではないことがよくあります。だから、実際にinstance_methods
に頼ることはできません。
1
これはあなたが探していた結果ですか?
class Foo
def bar
p "bar"
end
end
p Foo.public_instance_methods(false) # => [:bar]
私は、これは後にあなたがいた結果ではなかった期待PS:私は指摘したようにhttps://github.com/bf4/Notes/blob/master/code/ruby_inspection.rb
の1点で、これらすべての検査方法を文書化しようとし始めた
p Foo.public_methods(false) # => [:allocate, :new, :superclass]
0
他の回答:
class Foo; def bar; end; def self.baz; end; end
第一に、私はあなたのオプションが
Foo.public_methods.sort.grep /methods/ # all public class methods matching /method/
# ["instance_methods", "methods", "private_instance_methods", "private_methods", "protected_instance_methods", "protected_methods", "public_instance_methods", "public_methods", "singleton_methods"]
Foo.new.public_methods.sort.grep /methods/
# ["methods", "private_methods", "protected_methods", "public_methods", "singleton_methods"]
はまたhttps://stackoverflow.com/questions/123494/whats-your-favourite-irb-trick
おそらく、あなたは 'のような何かにあなたの例を変更してくださいを参照してくださいしているかを調べるためのメソッド
に便利な先端をGrepを並べ替えることが好き'.public_methods'または '[] .public_methods'を使用してください。 Rubyを知っている人にとっては、あなたの例が 'Array'クラスのオブジェクト*自身が*応答するメソッドと' Array'クラスのインスタンスメソッドではないメソッドをリストしているのは明らかですが、初心者にとっては誤解を招くかもしれません。 –
@JörgWMittagありがとうございました。 ArrayクラスやStringインスタンスにはメソッドが多すぎるため、SOコードブロックが行を折り返さないため、私はカスタムクラスを使いました。結果が同じではないことはすぐには分かりませんでした。 –