TkVariables and ".value" method

The code below, which puts “Hello” in a label on press of a button,
works if the command for the button is { a.value = “Hello” }, but not if
it is { a = “Hello” }. I’m trying to understand “why”, and can’t find
anything on the “.value” method in in the Pragmatic Programmers’ book on
Ruby.

Can someone explain why {a = “Hello”} won’t work, and why I need to do
{a.value = “Hello”?}

Thanks in advance.


require ‘tk’

root = TkRoot.new.title(“Example”)

a = TkVariable.new
Labels = TkLabel.new(root) do
textvariable a
pack(‘side’ => “top”)
end

TkButton.new(root) do
text “Press”
command { a.value = “Hello” }
pack(‘side’ => “top”)
end

Tk.mainloop

On Thu, Mar 08, 2007 at 11:40:09PM +0900, Alex DeCaria wrote:

The code below, which puts “Hello” in a label on press of a button,
works if the command for the button is { a.value = “Hello” }, but not if
it is { a = “Hello” }. I’m trying to understand “why”, and can’t find
anything on the “.value” method in in the Pragmatic Programmers’ book on
Ruby.

http://rubycentral.com/book/tut_classes.html
Scroll down to “Writable Attributes”

Can someone explain why {a = “Hello”} won’t work, and why I need to do
{a.value = “Hello”?}

a = TkVariable.new # ‘a’ points to an instance of TkVariable

a.value = “Hello” # calls method ‘value=’ on this object,
# with “Hello” as the argument. Afterwards,
# ‘a’ still points to the same TkVariable
object

BUT:

a = TkVariable.new # ‘a’ points to an instance of TkVariable

a = “Hello” # ‘a’ now points to a completely different
object,
# which is a string. The TkVariable is not
# referenced from anywhere, and will be
# garbage-collected at some point

Try this in irb, see if it makes it any clearer:

class Foo
def bar=(x)
@q = x
end

def bar
  @q
end

end

a = Foo.new
puts a.inspect
a.bar = 99
puts a.inspect
a = 123
puts a.inspect

Brian.