On Fri, Feb 5, 2010 at 11:42 AM, Cnm Cnm <opti900 / gmail.com> wrote:
> 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

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.