# TkVariables and ".value" method

**URL:** <https://www.ruby-forum.com/t/tkvariables-and-value-method/88155>\
**Category:** Ruby\
**Created:** [March 8, 2007, 3:40pm UTC](https://www.ruby-forum.com/t/tkvariables-and-value-method/88155 "2007-03-08T15:40:07Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![alexd](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/96bed5/32.png) [@alexd](https://www.ruby-forum.com/u/alexd)\
**Post date:** [March 8, 2007, 3:40pm UTC](https://www.ruby-forum.com/t/tkvariables-and-value-method/88155/1 "2007-03-08T15:40:07Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![alexd](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/96bed5/32.png) [@alexd](https://www.ruby-forum.com/u/alexd)\
**Post date:** [March 8, 2007, 3:58pm UTC](https://www.ruby-forum.com/t/tkvariables-and-value-method/88155/2 "2007-03-08T15:58:14Z")

</div>

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](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.
