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.
Did changed language definition recently somehow or is the example
and/or description in the book simply flawed ?
myobj.outer_const and instance methods defined in the anonymous class
have the same context, which is expected to be differerent from that of
the top level. MYCONST in both places binds to the same `self’ (myobj).
Su Zhang> Thanks, but that confirms my results. The books preface states
it covers Ruby ver. 1.9.1 and I would wonder if it’s valid no more for
Ruby 1.9.2 ?
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.