views:

43

answers:

1

Hi,

given this code:

class Foo
  def bar
    return Bar.new
  end
end

class Bar
  ...
end

I get this error:

NameError: uninitialized constant Bar

This obviously works if I put Bar before Foo but that is not a real solution though.

Any ideas on how to solve this without considering the order?

Many thanks.

UPDATE:

Of course the error occurs only when calling Foo.new.bar and not when defining.

+3  A: 

There must be something wrong with your installation of Ruby. It shouldn't give that error message. I checked with the ISO Ruby specification and the RubySpec and I also copy & pasted the code you posted into JRuby 1.6.0.dev, JRuby 1.5.0RC3, IronRuby 1.0, YARV 1.9.1-p378, MRI 1.8.7-p249, Rubinius 0.11.0-dev, YARV-1.9.1-p129, MRI 1.8.7-p174, MRI 1.8.6-p369, MRI 1.7.1, MRI 1.6.0, MRI 1.5.0, MRI 1.4.0, MRI 1.3, MRI 1.2 and even MRI 1.0 (going all the way back to 1997) and I didn't get that error:

class Foo
  def bar
    return Bar.new
  end
end

class Bar
end

puts Foo.new.bar # => #<Bar:0x823f638>
Jörg W Mittag
+1 for comprehensiveness of test environments
pilcrow
You are absolutely right. I can not reproduce the error now after I made some changes to my code. But I was convinced that it is due to the define order as I thought I experienced the same issue some time ago.My fault... for not investigating further before posting.
bresc