In Ruby, if global_variables.class returns Array, how do you determine if global_variables is an array or method?

In Ruby, if global_variables.class returns an Array , how do you determine if global_variables array or method?

+4
source share
3 answers

Lay it out:

 >> 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 >> 
+7
source

Typically, global methods are defined by Kernel, which is the ancestor of Object. All methods written outside the 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] 
0
source

When Ruby sees a single word, it always checks first whether there is a local variable with that name. If not, it tries to call the method:

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

If it cannot resolve the name as a local var or method, you will receive the following error:

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

Since you have not previously assigned 'global_variables', this should be a method.

0
source

Source: https://habr.com/ru/post/1313732/


All Articles