在Ruby中,如果“global_variables.class”返回“Array”,那么如何判断global_variables是数组还是方法?

时间:2010-06-24 06:17:42

标签: ruby class types

在Ruby中,如果global_variables.class返回Array,您如何判断global_variables是数组还是方法?

3 个答案:

答案 0 :(得分:7)

挖掘这个:

>> global_variables
=> ["$-l", "$LOADED_FEATURES", "$?", ... , "$SAFE", "$!"]
>> method(:global_variables)
=> #<Method: Object(Kernel)#global_variables>

进行比较:

>> method(:foo)
NameError: undefined method `foo' for class `Object'
    from (irb):6:in `method'
    from (irb):6
>> 

答案 1 :(得分:0)

通常全局方法由内核定义,内核是Object的祖先。在类外部编写的所有方法都被视为Object的私有方法。

irb(main):031:0> Object.private_methods.select{|x| x.to_s.start_with? 'gl'}
=> [:global_variables]

irb(main):032:0> f = [1,2,3]
=> [1, 2, 3]
irb(main):033:0> f.class
=> Array
irb(main):037:0> Object.private_methods.select{|x| x.to_s.start_with? 'f'}
=> [:format, :fail, :fork]

答案 2 :(得分:0)

当Ruby看到一个裸字时,它总是首先检查是否存在具有该名称的局部变量。如果没有,它会尝试调用方法:

>> def foo
..   "bar"
..   end
=> nil
>> foo = "lala"
=> "lala"
>> foo
=> "lala"
>> # to explicitly call the method
..   foo()
=> "bar"

如果无法将名称解析为本地var或方法,则会出现以下错误:

>> bar
NameError: undefined local variable or method `bar' for #<Object:0x000001008b8e58>
    from (irb):1

由于您之前没有分配给'global_variables',因此它必须是一种方法。