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?
quik77
October 21, 2011, 1:30pm
2
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
quik77
October 21, 2011, 2:39pm
3
…
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
quik77
October 21, 2011, 2:50pm
4
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! Now I see it, too.
Kind regards
robert
quik77
October 21, 2011, 2:52pm
5
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.
quik77
October 21, 2011, 2:46pm
6
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.