...ジェネリックオブジェクトのすべてのパブリックメソッドを含めずに? つまり、配列の減算を行うこと以外です。ドキュメントにアクセスせずに、オブジェクトから利用できるものをすばやく確認したいだけです。
4 に答える
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 が指摘したように、動的に定義されたメソッド ( withmethod_missing
など) はここには表示されません。これらのライブラリに対する唯一の賭けは、使用しているライブラリが十分に文書化されていることを期待することです。
これはあなたが探していた結果ですか?
class Foo
def bar
p "bar"
end
end
p Foo.public_instance_methods(false) # => [:bar]
psこれはあなたが望んでいた結果ではなかったと思います:
p Foo.public_methods(false) # => [:allocate, :new, :superclass]
私はhttps://github.com/bf4/Notes/blob/master/code/ruby_inspection.rbでこれらすべての検査方法を一度に文書化しようとし始めました
他の回答に記載されているように:
class Foo; def bar; end; def self.baz; end; end
まず、メソッドを並べ替えるのが好きです
Foo.public_methods.sort # all public instance methods
Foo.public_methods(false).sort # public class methods defined in the class
Foo.new.public_methods.sort # all public instance methods
Foo.new.public_methods(false).sort # public instance methods defined in the class
オプションが何であるかを知るための便利なヒントGrep
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も参照してください
もしあったとしても、それはあまり役に立たないでしょう: 動的メタプログラミングによってメソッドを偽造する Ruby の能力のために、多くの場合、public メソッドは唯一の選択肢ではありません。instance_methods
そのため、役に立つことをたくさん教えてくれるとは限りません。