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 ?
The context is expected to differ from the top level inside
myobj.outer_const as well as inside instance methods of inner_const,
because they are binding-identical singleton methods. MYCONST in both
palces binds to the same `self', which is myobj =)
puts "Top level: #{self}"
myobj = Object.new
class << myobj
def foo
puts "class << myobj; def foo: #{self}"
end
end
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 ?
On Mon, Nov 29, 2010 at 5:30 PM, David Unric <dunric29a@gmail.com> 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.
On Tue, Nov 30, 2010 at 9:58 AM, Robert Klemme <shortcutter@googlemail.com>wrote:
On Mon, Nov 29, 2010 at 5:30 PM, David Unric <dunric29a@gmail.com> 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.