mon*_*kut 34 ruby introspection irb
我是红宝石的新手,我正在玩IRB.
我发现我可以使用".methods"方法列出对象的方法,而self.methods类似于我想要的东西(类似于Python的dir(builtins)?),但我怎样才能找到方法库/模块我通过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>
Run Code Online (Sandbox Code Playgroud)
我习惯了python,在那里我使用dir()函数来完成同样的事情:
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__']
>>>
Run Code Online (Sandbox Code Playgroud)
web*_*mat 41
我不完全确定你对'当前物品'的意思.您可以迭代ObjectSpace,如前所述.但这里有一些其他方法.
local_variables
instance_variables
global_variables
class_variables
constants
Run Code Online (Sandbox Code Playgroud)
有一个问题.必须在正确的范围内调用它们.因此,在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", ...]
Run Code Online (Sandbox Code Playgroud)
但是嗯,如果你希望你的程序实际评估它们而不需要你那么明智地输入它们呢?诀窍是eval.
eval "@inst_var" #=> 42
global_variables.each do |v|
puts eval(v)
end
Run Code Online (Sandbox Code Playgroud)
必须在模块级别评估开头提到的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"
Run Code Online (Sandbox Code Playgroud)
这是在不同方向探索的一些技巧
"".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...", ...]
Run Code Online (Sandbox Code Playgroud)
Fir*_*aad 26
ObjectSpace.each_object可能就是你要找的东西.
要获取包含模块的列表,可以使用Module.included_modules.
您还可以使用object.respond_to检查对象是否根据具体情况响应方法?.
该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
Run Code Online (Sandbox Code Playgroud)
您可以将类,对象或任何内容传递给它(默认为当前范围).我们来试试吧......
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"]
Run Code Online (Sandbox Code Playgroud)
dir()还包括本地定义的变量,这很容易.打电话给...
local_variables
Run Code Online (Sandbox Code Playgroud)
...遗憾的是,我们不能只是添加local_variables调用,included_methods因为它会为我们提供included_methods方法本地的变量,而且这不会非常有用.所以,如果你想在included_methods中包含局部变量,只需调用...
(included_methods + local_variables).sort
Run Code Online (Sandbox Code Playgroud)
小智 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
Run Code Online (Sandbox Code Playgroud)
我正在努力改进传递选项和设置默认值,但是现在我建议您将以下内容添加到.irbrc文件中:
require 'method_info'
MethodInfo::OptionHandler.default_options = {
:ancestors_to_exclude => [Object],
:enable_colors => true
}
Run Code Online (Sandbox Code Playgroud)
这使得颜色和隐藏每个对象具有的方法,因为您通常对这些方法不感兴趣.
| 归档时间: |
|
| 查看次数: |
30526 次 |
| 最近记录: |