ルビーの現在のスコープで現在利用可能なオブジェクトをどのようにリストしますか?
-
04-07-2019 - |
質問
ルビーは初めてで、IRBで遊んでいます。
<!> quot; .methods <!> quot;を使用してオブジェクトのメソッドを一覧表示できることがわかりました。メソッド、およびself.methodsは、私に欲しいものを与えます(Pythonのdir( builtins )に似ていますか?)必要ですか?
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>
私はpythonに慣れており、dir()関数を使用して同じことを実現しています:
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__']
>>>
解決
ObjectSpace.each_object はどうなるかあなたが探しています。
含まれるモジュールのリストを取得するには、 Module.included_modules 。
他のヒント
「現在のオブジェクト」が何を意味するのか完全にはわかりません。既に述べたように、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", ...]
しかし、うーん、プログラムで何度も入力することなく実際にそれらを評価したい場合はどうでしょうか?秘Theは評価です。
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...", ...]
dir()
メソッドは明確に定義されていない ...
注:
included_modules
が提供されているため 主に次の場所での使用の便宜として 対話型プロンプト、それはしようとします 興味深い名前のセットを提供する 提供しようとする以上のもの 厳密または一貫して定義されたセット の名前とその詳細な動作 リリース間で変更される可能性があります。
...しかし、Rubyで厳密な近似を作成できます。含まれるモジュールによってスコープに追加されたすべてのメソッドのソートされたリストを返すメソッドを作成しましょう。 print
メソッドを使用して、含まれているモジュールのリストを取得できます。
Kernel
と同様に、<!> quot; default <!> quot;を無視します。メソッド(false
など)、および<!> quot; interesting <!> quot;名前のセット。したがって、methods()
のメソッドは無視し、継承されたメソッドを無視して、モジュールで直接定義されたメソッドのみを返します。後でlocal_variables
をincluded_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"]
<=>にはローカルで定義された変数も含まれますが、これは簡単です。ただ電話する...
local_variables
...残念ながら、<=>メソッドにローカルな変数を提供するため、<=>呼び出しを<=>に追加することはできません。これはあまり有用ではありません。したがって、included_methodsにローカル変数を含める場合は、単に呼び出します...
(included_methods + local_variables).sort
そのための宝石を書きました:
$ 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
}
これにより色が有効になり、すべてのオブジェクトが持つメソッドが非表示になります。通常はそれらに興味がないためです。
概要:
Object.constants.select{|x| eval(x.to_s).class == Class}
それは私が利用できるクラスをリストしています。私はルビーの専門家ではなく、どのクラスが手元にあるのかわからないままルビーコンソールに落とされていました。そのライナーが出発点でした。
Rubyのすべてのオブジェクトインスタンスにアクセスするには、ObjectSpaceを使用します
http://www.ruby-doc .org / core-1.8.7 / classes / ObjectSpace.html#M000928
ただし、これは(Rubyの場合でも)遅いと見なされ、一部のインタープリターでは有効にならない場合があります(たとえば、jRubyでjstuffを追跡する必要なくgcのjvmに依存するため、jRubyはObjectSpaceを無効にできます)。
.methodsメッセージをライブラリ/モジュールに渡してからロードしてから、使用可能なすべてのメソッドを確認できます。 self.methods
を実行すると、Objectオブジェクトに含まれるすべてのメソッドが返されます。これを確認するには、self.class
を実行します。それでは、Fileモジュールのすべてのメソッドを見たいとしましょう。 File.methods
を実行するだけで、Fileモジュールに存在するすべてのメソッドのリストを取得できます。これはおそらくあなたが望むものではありませんが、いくらか役立つはずです。