Hi all,
I was wondering what happened in the background of following snippet.
First I define a method v1, and I am able to call v1. Then I redefine v1
as an array; after that I can only call v1 as a function by calling
v1(). How does ruby look up v1 as a function and variable? Thanks
irb(main):001:0> def v1
irb(main):002:1> puts ‘printing from method v1’
irb(main):003:1> end
=> nil
irb(main):004:0> v1
printing from method v1
=> nil
irb(main):005:0> v1 = []
=> []
irb(main):006:0> v1
=> []
irb(main):007:0> v1()
printing from method v1
=> nil
On Fri, Feb 5, 2010 at 11:42 AM, Cnm C. [email protected] wrote:
irb(main):004:0> v1
printing from method v1
=> nil
At this point, since you ONLY have method/function named ‘v1’ defined,
the interpreter unambiguously knows you’re making a call to that
method sans parenthesis.
irb(main):005:0> v1 = []
=> []
Now that you’ve ALSO created an Array instance stored in a variable
named ‘v1’ you can no longer call your function/method the way you did
before because the two items overlap by name (but both still exist
independently).
irb(main):006:0> v1
=> []
As you noted, the interpreter prefers the variable ‘v1’ over the method.
irb(main):007:0> v1()
printing from method v1
=> nil
Now that you added parenthesis, the interpreter knows you’re wanting
to call the method ‘v1’. You could also do:
method(:v1).call
Or:
send(:v1)
Those would also call the method.
How’s THIS for fun:
irb(main):001:0> def foo
irb(main):002:1> puts “This is the method foo()”
irb(main):003:1> end
=> nil
irb(main):004:0> foo
This is the method foo()
=> nil
irb(main):005:0> foo = method(:foo)
=> #<Method: Object#foo>
irb(main):006:0> foo
=> #<Method: Object#foo>
irb(main):007:0> foo()
This is the method foo()
=> nil
irb(main):008:0> foo.call
This is the method foo()
=> nil
I sure love Ruby!
Aaron out.
Aaron out.
On Feb 5, 2010, at 1:42 PM, Cnm C. wrote:
irb(main):004:0> v1
printing from method v1
At this point the only thing named ‘v1’ is a method
so the method is called.
=> nil
irb(main):005:0> v1 = []
=> []
Now there are two things named ‘v1’ a method
and a local variable. Name resolution prefers
local variables so…
irb(main):006:0> v1
=> []
The local variable is referenced
irb(main):007:0> v1()
printing from method v1
=> nil
By adding the explicit parens you’ve given Ruby
a hint that you want to call a method and not
lookup a local variable.
Alternatively you could do:
self.v1
which would also reference the method and not
the local variable.
Gary W.
Thanks Gary and Aaron. I understand it now.
Gary W. wrote:
On Feb 5, 2010, at 1:42 PM, Cnm C. wrote: