39

私はRubyが初めてで、IRBをいじっています。

「 .methods」メソッドを使用してオブジェクトのメソッドをリストできることがわかりました.self.methodsは私が望むものを与えてくれます. include および require を介してロードしたライブラリ/モジュール?

irb(main):036:0* self.methods
=> ["irb_pop_binding", "inspect", "taguri", "irb_chws", "clone", "irb_pushws", "public_methods", "taguri=", "irb_pwws",
"public", "display", "irb_require", "irb_exit", "instance_variable_defined?", "irb_cb", "equal?", "freeze", "irb_context
", "irb_pop_workspace", "irb_cwb", "irb_jobs", "irb_bindings", "methods", "irb_current_working_workspace", "respond_to?"
, "irb_popb", "irb_cws", "fg", "pushws", "conf", "dup", "cwws", "instance_variables", "source", "cb", "kill", "help", "_
_id__", "method", "eql?", "irb_pwb", "id", "bindings", "send", "singleton_methods", "popb", "irb_kill", "chws", "taint",
 "irb_push_binding", "instance_variable_get", "frozen?", "irb_source", "pwws", "private", "instance_of?", "__send__", "i
rb_workspaces", "to_a", "irb_quit", "to_yaml_style", "irb_popws", "irb_change_workspace", "jobs", "type", "install_alias
_method", "irb_push_workspace", "require_gem", "object_id", "instance_eval", "protected_methods", "irb_print_working_wor
kspace", "irb_load", "require", "==", "cws", "===", "irb_pushb", "instance_variable_set", "irb_current_working_binding",
 "extend", "kind_of?", "context", "gem", "to_yaml_properties", "quit", "popws", "irb", "to_s", "to_yaml", "irb_fg", "cla
ss", "hash", "private_methods", "=~", "tainted?", "include", "irb_cwws", "irb_change_binding", "irb_help", "untaint", "n
il?", "pushb", "exit", "irb_print_working_binding", "is_a?", "workspaces"]
irb(main):037:0>

私は dir() 関数を使用して同じことを達成する Python に慣れています。

>>> dir()
['__builtins__', '__doc__', '__name__', '__package__']
>>>
4

7 に答える 7

48

「現在のオブジェクト」が何を意味するのか完全にはわかりません。すでに述べたように、ObjectSpace を反復処理できます。しかし、他の方法をいくつか紹介します。

local_variables
instance_variables
global_variables

class_variables
constants

落とし穴が 1 つあります。適切なスコープで呼び出す必要があります。したがって、IRB 内、オブジェクト インスタンス内、またはクラス スコープ内 (基本的にどこでも) で、最初の 3 つを呼び出すことができます。

local_variables #=> ["_"]
foo = "bar"
local_variables #=> ["_", "foo"]
# Note: the _ variable in IRB contains the last value evaluated
_ #=> "bar"

instance_variables  #=> []
@inst_var = 42
instance_variables  #=> ["@inst_var"]

global_variables    #=> ["$-d", "$\"", "$$", "$<", "$_", ...]
$"                  #=> ["e2mmap.rb", "irb/init.rb", "irb/workspace.rb", ...]

しかし、うーん、何度も入力しなくてもプログラムで実際に評価できるようにしたい場合はどうすればよいでしょうか? トリックは eval です。

eval "@inst_var" #=> 42
global_variables.each do |v|
  puts eval(v)
end

最初に述べた 5 つのうち最後の 2 つをモジュール レベルで評価する必要があります (クラスはモジュールの子孫であるため、機能します)。

Object.class_variables #=> []
Object.constants #=> ["IO", "Duration", "UNIXserver", "Binding", ...]

class MyClass
  A_CONST = 'pshh'
  class InnerClass
  end
  def initialize
    @@meh = "class_var"
  end
end

MyClass.constants           #=> ["A_CONST", "InnerClass"]
MyClass.class_variables     #=> []
mc = MyClass.new
MyClass.class_variables     #=> ["@@meh"]
MyClass.class_eval "@@meh"  #=> "class_var"

さまざまな方向で探索するためのいくつかのトリックを次に示します

"".class            #=> String
"".class.ancestors  #=> [String, Enumerable, Comparable, ...]
String.ancestors    #=> [String, Enumerable, Comparable, ...]

def trace
  return caller
end
trace #=> ["(irb):67:in `irb_binding'", "/System/Library/Frameworks/Ruby...", ...]
于 2008-10-25T06:18:48.637 に答える
29

ObjectSpace.each_objectは、探しているものである可能性があります。

含まれているモジュールのリストを取得するには、Module.included_modulesを使用できます。

object.respond_to?を使用して、オブジェクトがメソッドに応答するかどうかをケースバイケースで確認することもできます。.

于 2008-10-23T08:13:27.637 に答える
6

dir()メソッドは明確に定義されていません...

注:は主に対話型プロンプトでの使用を便利にするためdir()に提供されているため、厳密にまたは一貫して定義された一連の名前を提供しようとするよりも、興味深い一連の名前を提供しようとします。詳細な動作はリリース間で変わる可能性があります。

...しかし、Ruby では近似値を作成できます。インクルードされたモジュールによってスコープに追加されたすべてのメソッドのソートされたリストを返すメソッドを作成しましょう。included_modulesメソッドを使用して、含まれているモジュールのリストを取得できます。

のようdir()に、「デフォルト」のメソッド ( などprint) を無視し、「興味深い」名前のセットに注目したいと考えています。したがって、 のメソッドはKernel無視し、継承されたメソッドを無視して、モジュールで直接定義されたメソッドのみを返します。メソッドに渡すことで、後者を実現できfalseますmethods()。すべてをまとめると...

def included_methods(object=self)
  object = object.class if object.class != Class
  modules = (object.included_modules-[Kernel])
  modules.collect{ |mod| mod.methods(false)}.flatten.sort
end

クラス、オブジェクト、または何も渡すことができません (デフォルトでは現在のスコープになります)。試してみましょう...

irb(main):006:0> included_methods
=> []
irb(main):007:0> include Math
=> Object
irb(main):008:0> included_methods
=> ["acos", "acosh", "asin", "asinh", "atan", "atan2", "atanh", "cos", "cosh", "erf", "erfc", "exp", "frexp", "hypot", "ldexp", "log", "log10", "sin", "sinh", "sqrt", "tan", "tanh"]

dir()ローカルで定義された変数も含まれており、これは簡単です。電話するだけ...

local_variables

local_variables...残念ながら、呼び出しを追加するだけincluded_methodsでは、メソッドにローカルな変数が得られてしまい、included_methodsあまり役に立ちません。したがって、included_methods に含まれるローカル変数が必要な場合は、呼び出してください...

 (included_methods + local_variables).sort
于 2008-10-24T02:13:05.523 に答える
6

私はそのための宝石を書きました:

$ gem install method_info
$ rvm use 1.8.7 # (1.8.6 works but can be very slow for an object with a lot of methods)
$ irb
> require 'method_info'
> 5.method_info
::: Fixnum :::
%, &, *, **, +, -, -@, /, <, <<, <=, <=>, ==, >, >=, >>, [], ^, abs,
div, divmod, even?, fdiv, id2name, modulo, odd?, power!, quo, rdiv,
rpower, size, to_f, to_s, to_sym, zero?, |, ~
::: Integer :::
ceil, chr, denominator, downto, floor, gcd, gcdlcm, integer?, lcm,
next, numerator, ord, pred, round, succ, taguri, taguri=, times, to_i,
to_int, to_r, to_yaml, truncate, upto
::: Precision :::
prec, prec_f, prec_i
::: Numeric :::
+@, coerce, eql?, nonzero?, pretty_print, pretty_print_cycle,
remainder, singleton_method_added, step
::: Comparable :::
between?
::: Object :::
clone, to_yaml_properties, to_yaml_style, what?
::: MethodInfo::ObjectMethod :::
method_info
::: Kernel :::
===, =~, __clone__, __id__, __send__, class, display, dup, enum_for,
equal?, extend, freeze, frozen?, hash, id, inspect, instance_eval,
instance_exec, instance_of?, instance_variable_defined?,
instance_variable_get, instance_variable_set, instance_variables,
is_a?, kind_of?, method, methods, nil?, object_id, pretty_inspect,
private_methods, protected_methods, public_methods, respond_to?, ri,
send, singleton_methods, taint, tainted?, tap, to_a, to_enum, type,
untaint
 => nil

オプションと設定のデフォルトを渡す改善に取り組んでいますが、今のところ、.irbrc ファイルに以下を追加することをお勧めします。

require 'method_info'
MethodInfo::OptionHandler.default_options = {
 :ancestors_to_exclude => [Object],
 :enable_colors => true
}

これにより、色が有効になり、すべてのオブジェクトが持つメソッドが非表示になります。これは、通常、それらに関心がないためです。

于 2010-11-09T11:06:38.377 に答える
4

どうですか:

Object.constants.select{|x| eval(x.to_s).class == Class}

それは私のために利用可能なクラスをリストします。私は Ruby の専門家ではなく、どのクラスが手元にあるのかわからないまま、Ruby コンソールに落とされていました。その1つのライナーが始まりでした。

于 2016-07-27T22:27:25.053 に答える
2

Ruby ですべてのオブジェクト インスタンスにアクセスするには、ObjectSpace を使用します。

http://www.ruby-doc.org/core-1.8.7/classes/ObjectSpace.html#M000928

ただし、これは (ruby の場合でも) 遅いと見なされ、一部のインタープリターでは有効にできない場合があります (たとえば、jRuby でこのようなことを追跡する必要がなく、gc の jvm に依存する方がはるかに高速であるため、jRuby は ObjectSpace を無効にできます)。

于 2008-10-23T08:07:04.187 に答える
0

ライブラリ/モジュールをロードする前であっても、.methods メッセージをライブラリ/モジュールに渡して、使用可能なすべてのメソッドを表示できます。self.methods実行すると、Object オブジェクトに含まれるすべてのメソッドが返されます。を実行すると、これを確認できますself.class。それでは、File モジュールのすべてのメソッドを見たいとしましょう。実行するだけFile.methodsで、File モジュールに存在するすべてのメソッドのリストが表示されます。これはおそらくあなたが望むものではありませんが、多少は役立つはずです。

于 2008-10-23T08:06:06.700 に答える