当前位置:  开发笔记 > 编程语言 > 正文

如何在ruby中列出当前作用域中当前可用的对象?

如何解决《如何在ruby中列出当前作用域中当前可用的对象?》经验,为你挑选了4个好方法。

我是红宝石的新手,我正在玩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>

我习惯了python,在那里我使用dir()函数来完成同样的事情:

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

webmat.. 41

我不完全确定你对'当前物品'的意思.您可以迭代ObjectSpace,如前所述.但这里有一些其他方法.

local_variables
instance_variables
global_variables

class_variables
constants

有一个问题.必须在正确的范围内调用它们.因此,在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...", ...]


Firas Assaad.. 26

ObjectSpace.each_object可能就是你要找的东西.

要获取包含模块的列表,可以使用Module.included_modules.

您还可以使用object.respond_to检查对象是否根据具体情况响应方法?.



1> webmat..:

我不完全确定你对'当前物品'的意思.您可以迭代ObjectSpace,如前所述.但这里有一些其他方法.

local_variables
instance_variables
global_variables

class_variables
constants

有一个问题.必须在正确的范围内调用它们.因此,在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...", ...]



2> Firas Assaad..:

ObjectSpace.each_object可能就是你要找的东西.

要获取包含模块的列表,可以使用Module.included_modules.

您还可以使用object.respond_to检查对象是否根据具体情况响应方法?.



3> two-bit-fool..:

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



4> 小智..:

我为此写了一个宝石:

$ 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
}

这使得颜色和隐藏每个对象具有的方法,因为您通常对这些方法不感兴趣.


我猜这不是问题的真正意义但是jeebus这就是我所需要的irb.mixin的广泛使用导致了太多的方法使得ruby库比python更难以探索,但是这应该很好地帮助解决这个问题.现在我只需要替换帮助()就好了.
推荐阅读
家具销售_903
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有