2008-10-23 89 views
33

我是新来的红宝石,我正在玩IRB。如何在ruby中列出当前范围内的当前可用对象?

我发现我可以列出使用“方法”的方法,对象的方法和self.methods那种给我什么,我想(类似于Python的目录(内建)?),但如何能我找到了通过include和要求加载的库/模块的方法?

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()函数来完成同样的事情:

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

回答

0

,你甚至可以在加载之前通过的消息。方法对库/模块它,看到所有可用的方法。做self.methods只是返回Object对象包含的所有方法。你可以通过做self.class来看到。假设您想查看File模块中的所有方法。您只需执行File.methods,即可获得File模块中存在的所有方法的列表。这可能不是你想要的,但应该有所帮助。

5

dir()方法是not clearly defined ......

注:因为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 
+0

好吧,我在慢慢学习。这带来了我的下一个问题,“include”和“require”之间有什么区别?我会去做一些阅读,但是怎样才能看到通过“require”加载的方法? – monkut 2008-10-24 02:57:28

+1

include会将常量,方法和模块变量添加到当前作用域。它通常用于为类添加功能。 A需要加载另一个ruby文件(如果它尚未加载)。如果你想加载它(即使它已经加载),请改用“加载”方法。 – 2008-11-04 17:49:08

39

我不能完全肯定你的意思是“当前对象”是什么。正如已经提到的那样,你可以迭代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...", ...] 
5

我写了一个宝石探索:

$ 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 ::: 
%, &, *, **, +, -, [email protected], /, <, <<, <=, <=>, ==, >, >=, >>, [], ^, 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 ::: 
[email protected], 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 
} 

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

1

什么:

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

列出可用的类我。我不是红宝石专家,我被扔在一个红宝石控制台,不知道什么课程在手。那一班班轮是个开始。

相关问题