Here’s an example:
@tl_instance = “hello ruby”
puts @tl_instance
def tl_method
puts “from tl_method – @tl_instance: #{@tl_instance}”
end
tl_method
class Tl_class
def tlc_method
puts “from tlc_method – @tl_instance: #{@tl_instance}”
end
end
Tl_class.new.tlc_method
In tlc_method, I am unable to access @tl_instance. Presumably because
it’s an instance variable in some other class not Tl_class. But who’s
instance variable is it? Kernel? If so, how do I access it?
On Fri, 2007-08-17 at 00:09 +0900, Pito S. wrote:
tl_method
In tlc_method, I am unable to access @tl_instance. Presumably because
it’s an instance variable in some other class not Tl_class. But who’s
instance variable is it? Kernel? If so, how do I access it?
celtic@sohma:~$ ruby
puts “Self is #{self}”
puts “Self is of #{self.class}”
@i = 32
puts self.instance_variable_get(’@i’)
puts instance_variable_get(’@i’)
Self is main
Self is of Object
32
32
celtic@sohma:~$
You get the same results if you enter these in irb. The scope is an
Object called `main’, and all instance variables belong to it – not,
say, a class like Kernel.
Cheers,
Arlen.
Any instance variable refers to the object currently being self at the
moment.
@tl_instance = “hello ruby”
self here is “main”, which is the top level default object
puts @tl_instance
def tl_method
puts “from tl_method – @tl_instance: #{@tl_instance}”
end
self here is “main” too
tl_method
=> Working as expected
class Tl_class
def tlc_method
puts “from tlc_method – @tl_instance: #{@tl_instance}”
end
end
Tl_class.new.tlc_method
Inside tlc.method, self is the “Tl_class.new” object, which doesn’t know
about any @tl_instance.