From: David Jacobs Date: 2011-05-12T05:26:56+09:00 Subject: Re: Scope problem (?) in implementing Design Patterns in Ruby --000e0cdfc918a9803304a305e489 Content-Type: text/plain; charset=ISO-8859-1 I think the lookup starts at the innermost scope but since All isn't defined in Not, it reaches the top-level. On Wed, May 11, 2011 at 4:23 PM, 7stud -- wrote: > 7stud -- wrote in post #998081: > > RichardOnRails wrote in post #998059: > >> > > > > 1) Your case statement syntax doesn't work in ruby 1.9.2: > > > > prog.rb:4: syntax error, unexpected ':', expecting keyword_then or ',' > > or ';' or '\n' > > > > You have to use 'then' in place of a colon. > > > > 2) Next, I get this error: > > > > prog.rb:67:in `evaluate': uninitialized constant Not::All (NameError) > > from prog.rb:74:in `
' > > > > which relates to this code: > > > > class Not < Expression > > def initialize(expression) > > @expression = expression > > end > > > > def evaluate(dir) > > all = All.new.evaluate(dir) > > other = @expression.evaluate(dir) > > all - other > > end > > end > > > > In ruby, constants are looked up like directories and files (or if you > > prefer constants are 'lexically scoped'). When you > > are inside the Not class (which is a module), the 'directory' you are in > > for constant lookups is the 'Not' directory. When you write All.new, > > because the name All is not preceded by a directory name, ruby looks in > > the current 'directory' for the constant All. The current directory is > > Not, so ruby is looking for Not::All, i.e. the 'file' All in the > > 'directory' Not. However, All is not defined inside Not, so you get an > > error. In fact, there is no constant named All defined anywhere in > > your program, so the error is more serious than a scope problem. > > > > If you are inside a class/module and you need to access a class at the > > top level, you do this: > > > > class All > > def greet > > puts 'hi' > > end > > end > > > > > > class Dog > > def do_stuff > > ::All.new.greet #<***** > > end > > end > > > > Dog.new.do_stuff #=>hi > > > > In fact, that is unnecessary: > > class All > def greet > puts 'hi' > end > end > > > class Dog > def do_stuff > All.new.greet #<***** > end > end > > Dog.new.do_stuff #=>hi > > > I guess the lookup actually starts at the toplevel. So your error is a > result of not defining the constant All at the toplevel, and ruby > obfuscates the error by telling you that All is not defined inside the > Not module, giving you the error message: Not::All doesn't exist. > > -- > Posted via http://www.ruby-forum.com/. > > --000e0cdfc918a9803304a305e489--