From: Josh Cheek Date: 2010-12-01T01:07:05+09:00 Subject: Re: Confusion about singleton method definition --0016e68db81c22deb8049647611f Content-Type: text/plain; charset=ISO-8859-1 On Tue, Nov 30, 2010 at 9:58 AM, Robert Klemme wrote: > 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/ > > I get that result for 1.9.2 $ rvm r.rb 1.8.7(jruby-1.5.2) 333 666 1.8.7(jruby-1.5.3) 333 666 1.9.2(macruby-0.7) 333 666 1.8.7(rbx-1.1.0-20100923) 333 666 1.8.6(ruby-1.8.6-p399) 333 666 1.8.7(ruby-1.8.7-p249) 333 666 1.8.7(ruby-1.8.7-p302) 333 666 1.9.1(ruby-1.9.1-p378) 333 666 1.9.2(ruby-1.9.2-p0) 333 333 $ 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 puts "#{RUBY_VERSION}(#{ENV['RUBY_VERSION']})" myobj.inner_const myobj.outer_const --0016e68db81c22deb8049647611f--