When is a method known to Ruby?

Hi.

When is a method “known” to the ruby parser and why?

Example 1, works:


require ‘pp’

module Foo

def self.foo(i) # i is a string that will be shortened.
  return i.chop
end

CONSTANT_1 = 'bla'
CONSTANT_2 = foo('bla')

end

constants = Foo.constants
pp Foo.foo ‘abc’
pp Foo::CONSTANT_2
pp constants

This works, returns:

“ab”

“bl”

[“CONSTANT_1”, “CONSTANT_2”]


Example 2, does not work:


require ‘pp’

module Foo

CONSTANT_1 = 'bla'
CONSTANT_2 = foo('bla')

def self.foo(i) # i is a string that will be shortened.
  return i.chop
end

end

constants = Foo.constants
pp Foo.foo ‘abc’
pp Foo::CONSTANT_2
pp constants

This does not work, returns:

module_test.rb:6: undefined method `foo’ for Foo:Module

(NoMethodError)


The difference is when def self.foo(i)
appears.

Apparently the parser must have “seen” it before working on it.

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

On Fri, Oct 21, 2011 at 1:10 PM, Marc H. [email protected]
wrote:

pp Foo.foo ‘abc’

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

module Foo

CONSTANT_1 = ‘bla’
CONSTANT_2 = foo(‘bla’)

def self.foo(i) # i is a string that will be shortened.

As Robert described, the call to foo in assignment to CONSTANT_2
occurs before foo is defined

cheers

On Fri, Oct 21, 2011 at 2:45 PM, Josh C. [email protected]
wrote:

On Fri, Oct 21, 2011 at 6:30 AM, Robert K.
[email protected]wrote:

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

In the first example, Foo.foo is defined before it is called in CONSTANT_2’s
initialization. In the second, CONSTANT_2 is initialized with Foo.foo before
it is defined.

Thanks for helping my feeble eyes, Josh! :wink: Now I see it, too.

Kind regards

robert

On 10/21/2011 07:10 AM, Marc H. wrote:

Hi.

When is a method “known” to the ruby parser and why?

When the source module contain it is evaluated, at the time the lines of
code are evaluated.

On Fri, Oct 21, 2011 at 6:30 AM, Robert K.
[email protected]wrote:

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

In the first example, Foo.foo is defined before it is called in
CONSTANT_2’s
initialization. In the second, CONSTANT_2 is initialized with Foo.foo
before
it is defined.