From: 7stud -- Date: 2012-11-27T02:49:07+09:00 Subject: Re: Novice: Understanding instance 'variables' and methods Steve Tu wrote in post #1086523: > > So far, my understanding was that both methods and variables used lower > case names, That's true. > and that methods could be written both with and without > '()'. > That's correct. > To me that then made the t.test line a bit confusing, as it > appears to invoke the method test on t. > It does. > How then could you ever access > the instance variable test of t? > puts t.instance_variable_get(:@test) Or, you can reopen the class and redefine test(): class Test def test @test end end result = t.test puts result --output:-- 10 However, the example you posted is terrible, and no one would ever write code like that. > Am I then also right in assuming that in Ruby there aren't any true > visible instance variables, > Instance variables are "private" in ruby. That means you cannot directly access an instance variable--instead you have to use a method to accesses an instance variable. > as to make the variable visible, you have to > include an accessor - which effectively creates the getter/setter of > that variable? > You can either write an accessor by hand: def test @test end Or, you can tell ruby to do it for you: class Dog attr_reader :test def initialize(t) @test = t end end d = Dog.new(10) puts d.test --output:-- 10 > So if I changed the above code to have an instance variable of 'value', > with an accessor, I could then have: > > > @test = @value = 10 > No. You could write something like: class Dog attr_reader :test attr_accessor :value def initialize(t) @test = t end end d = Dog.new(10) d.value = 'hello' #setter puts d.value #getter > BUT t.value is then really a > call to the 'generated' getter of value - so is really a method call? > Yes. In fact, when you write: x = 1 + 2 "+" is actually the name of an Integer method. And because "+" is the name of a method, you can write that line like this: x = 1.+(2) puts x --output:-- 3 > 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? Who cares? You would never write a class that has two methods with the same name. -- Posted via http://www.ruby-forum.com/.