In Ruby, if global_variables.class
returns Array
, how do you tell whether global_variables
is an array or a method?
views:
42answers:
3
+7
A:
Dig this:
>> global_variables
=> ["$-l", "$LOADED_FEATURES", "$?", ... , "$SAFE", "$!"]
>> method(:global_variables)
=> #<Method: Object(Kernel)#global_variables>
For comparison:
>> method(:foo)
NameError: undefined method `foo' for class `Object'
from (irb):6:in `method'
from (irb):6
>>
Eimantas
2010-06-24 06:22:08
works... although I was more looking for a way to say something like `classof? global_variables => method`
動靜能量
2010-06-24 19:10:02
You can also do something like `defined?(global_variables)` which will return you string `"method"`.
Eimantas
2010-06-25 04:41:41
A:
Usually the global methods are defined by Kernel, which is an ancestor of Object. All methods written outside of a class are treated as private methods of 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]
Gishu
2010-06-24 06:24:05
A:
When Ruby sees a bareword, it always checks first if there is a local variable with that name. If there isn't, it tries to call a method:
>> def foo
.. "bar"
.. end
=> nil
>> foo = "lala"
=> "lala"
>> foo
=> "lala"
>> # to explicitly call the method
.. foo()
=> "bar"
If it can't resolve the name as either a local var or method, you get the following error:
>> bar
NameError: undefined local variable or method `bar' for #<Object:0x000001008b8e58>
from (irb):1
Since you didn't assign to 'global_variables' before, it has to be a method.
Michael Kohl
2010-06-24 12:01:38