From: Robert Klemme Date: 2010-12-01T00:58:04+09:00 Subject: Re: Confusion about singleton method definition On Mon, Nov 29, 2010 at 5:30 PM, David Unric wrote: > I'm just learning Ruby from The Well-grounded Rubist book and I cann't > understand why I cann't get the same results as in author's example. > > It's about the difference between defining singleton method directly on > an object and using class << construct. > Rephrased example follows: > > MYCONST=666 > > myobj = Object.new > > class << myobj >  MYCONST=333 > end > > def myobj.outer_const >  puts MYCONST > end > > class << myobj >  def inner_const >    puts MYCONST >  end > end > > > myobj.inner_const call displays 333 (singleton constant value) as > expected, > however myobj.outer_const call also displays 333 whereas it should > display the value of outer (global) MYCONST definition, ie. 666. Does it? 16:55:39 ~$ allruby r.rb CYGWIN_NT-5.1 padrklemme2 1.7.7(0.230/5/3) 2010-08-31 09:58 i686 Cygwin ======================================== ruby 1.8.7 (2008-08-11 patchlevel 72) [i386-cygwin] 333 666 ======================================== ruby 1.9.1p430 (2010-08-16 revision 28998) [i386-cygwin] 333 666 ======================================== jruby 1.4.0 (ruby 1.8.7 patchlevel 174) (2009-11-02 69fbfa3) (Java HotSpot(TM) Client VM 1.6.0_21) [x86-java] 333 666 16:55:55 ~$ cat r.rb MYCONST=666 myobj = Object.new class << myobj MYCONST=333 end def myobj.outer_const puts MYCONST end class << myobj def inner_const puts MYCONST end end myobj.inner_const myobj.outer_const 16:56:57 ~$ > Did changed language definition recently somehow or is the example > and/or description in the book simply flawed ? Can you show _exactly_ the code you executed? Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/