On Fri, Oct 21, 2011 at 1:10 PM, Marc Heiler <shevegen / linuxmail.org> wrote=
:
> Hi.
>
> When is a method "known" to the ruby parser and why?
>
> Example 1, works:
>
>
> =A0require 'pp'
>
> =A0module Foo
>
> =A0 =A0def self.foo(i) # i is a string that will be shortened.
> =A0 =A0 =A0return i.chop
> =A0 =A0end
>
> =A0 =A0CONSTANT_1 =3D 'bla'
> =A0 =A0CONSTANT_2 =3D foo('bla')
>
> =A0end
>
> =A0constants =3D Foo.constants
> =A0pp Foo.foo 'abc'
> =A0pp Foo::CONSTANT_2
> =A0pp constants
>
> =A0# This works, returns:
> =A0# "ab"
> =A0# "bl"
> =A0# =A0 ["CONSTANT_1", "CONSTANT_2"]
>
>
> Example 2, does not work:
>
> =A0require 'pp'
>
> =A0module Foo
>
> =A0 =A0CONSTANT_1 =3D 'bla'
> =A0 =A0CONSTANT_2 =3D foo('bla')
>
> =A0 =A0def self.foo(i) # i is a string that will be shortened.
> =A0 =A0 =A0return i.chop
> =A0 =A0end
>
> =A0end
>
> =A0constants =3D Foo.constants
> =A0pp Foo.foo 'abc'
> =A0pp Foo::CONSTANT_2
> =A0pp constants
>
> =A0# This does not work, returns:
> =A0# =A0module_test.rb:6: undefined method `foo' for Foo:Module
> (NoMethodError)
>
>
>
> The difference is when def self.foo(i)
> appears.

Frankly, I cannot see any difference (didn't try diff though).  Did
you really post what you tested?

> Apparently the parser must have "seen" it before working on it.

Yes, of course.  You cannot do

Foo.foo

module Foo
def self.foo end
end

nor can you do

module Foo
end

Foo.foo

module Foo
def self.foo end
end

> Can someone explain to me why, and if there is another workaround
> other than moving the method definition before the method call
> first happens?

We should first clarify what you _really_ did.

Cheers

robert



--=20
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/