Ross Bamford
1/15/2006 1:27:00 AM
On Sat, 14 Jan 2006 21:54:58 -0000, John Maclean <info@jayeola.org> wrote:
> Chaps,
>
> There's a small section of code from the second edition of the pickaxe
> book on p260.
>
> require 'tk'
>
> image1 = TkPhotoImage.new {file "img1.gif" }
> image2 = TkPhotoImage.new {file "img2.gif" }
>
> b = TkButton.new(@root) do # <---- This line
> # more code
> # not shown for sake of brevity
> end
> # more code
> # more code
> Am I right in saying that the line that creates the new button has an
> instance variable that will be used to define the main root "container"?
>
Yes, that is an instance var. However, it's unset, so the above line is
equivalent to:
b = TkButton.new(nil) do
or just:
b = TkButton.new do
As it says on p256:
"It's a good habit to specify the root explicitly, but you could
leave it out -- along with the options -- [...]"
So I guess it creates it implicitly in this case. Maybe it's a typo, or
maybe a (rather confusing IMO) way to demonstrate that the argument
carries the root element, or something. There's been discussion here
before about instance variables at the top level I think, search out the
archives. The following short script demonstrates a few points:
# find out about @foo
puts "Self is #<#{self.class}:#{self.object_id}> (#{self.inspect})"
# => Self is #<Object:-604402504> (main)
p instance_variables.member?('@foo') # => false
test = @foo # => nil
p instance_variables.member?('@foo') # => false
@foo = "test" # => "test"
p instance_variables.member?('@foo') # => true
p @foo # => "test"
p self.instance_variable_get(:@foo) # => "test"
p self.instance_eval { @foo } # => "test"
def foo
@foo
end
public :foo
p foo # => "test"
p self.foo # => "test"
p Array.foo # => nil
1.instance_eval { @foo = 'bar' }
p 1.foo # => "bar"
(P.s. that's definitely not an example to follow, more of a "Don't do it
this way!" thing ;))
Cheers,
--
Ross Bamford - rosco@roscopeco.remove.co.uk