TkVariables and ".value" method

A

Alex DeCaria

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
 
B

Brian Candler

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

Where is the extar end keyword. 2
Ruby/Tk 10
Ruby TK 2
How to Create a random password generator in a separate window 4
TkVarible question 4
Ruby/Tk 4
Ruby/tk Help Please 19
How can i 'Clear' a TkText...box??? 1

Members online

Forum statistics

Threads
473,774
Messages
2,569,596
Members
45,143
Latest member
SterlingLa
Top