From: Robert Klemme Date: 2011-10-21T20:30:00+09:00 Subject: Re: When is a method known to Ruby? On Fri, Oct 21, 2011 at 1:10 PM, Marc Heiler wrote: > 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. 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 -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/