From: "Jesús Gabriel y Galán" Date: 2012-11-27T02:36:49+09:00 Subject: Re: Novice: Understanding instance 'variables' and methods On Mon, Nov 26, 2012 at 5:49 PM, Steve Tucknott wrote: > A question - or comment - on instance variables. > > Looking at ':symbols' today, I came across this example: > > class Test > puts :Test.object_id.to_s > def test > puts :test.object_id.to_s > @test = 10 > puts :test.object_id.to_s > end > end > t = Test.new > t.test > > So far, my understanding was that both methods and variables used lower > case names, and that methods could be written both with and without > '()'. To me that then made the t.test line a bit confusing, as it > appears to invoke the method test on t. How then could you ever access > the instance variable test of t? > > Am I then also right in assuming that in Ruby there aren't any true > visible instance variables, as to make the variable visible, you have to > include an accessor - which effectively creates the getter/setter of > that variable? > > So if I changed the above code to have an instance variable of 'value', > with an accessor, I could then have: > > > @test = @value = 10 > > and then access t.value - giving me 10. BUT t.value is then really a > call to the 'generated' getter of value - so is really a method call? > > Do I have that about right? > > And in the above case, where a 'variable' and method have the same name, > is there a way to force the use of a specific 'setter/getter' - ie to > have t.test return the value of test, rather than call the method test > on t? As has been answered, you cannot get at the instance variables directly from the outside. It's all calling methods. But I think you have also another confusion, regarding *local* variables and methods: class A def test "test: the method" end def some_method test = "a variable" puts test #=> a variable puts self.test #=> test: the method puts test() #=> test: the method end end If you have a local variable and a method with the same name, the local variable "wins", and you have to use "self." or parenthesis to tell Ruby you want to call the method. Jesus.