Ruby parse order
given this code:
class Foo
def bar
return Bar.new
end
end
c开发者_开发技巧lass 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.
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>
精彩评论