So we have an instance of a person, how can we access the name variable? We can't! Instance variables are only available inside the class in Ruby. (Well, there's a super hacky way to get it, but ignore that)
We need to define a getter (and a setter, for the purposes of this example):
class Person
def initialize(name)
@name = name
end
def name
return @name
end
def name=(value)
@name = value
end
end
Our getter is a method called name
that returns the @name
instance variable.
p.name() #=> "Darryl"
One cool (and also confusing) thing about Ruby is that you can call methods without parentheses:
p.name
and p.name()
are both calling the name
method.
Our setter is called name=
and takes a value. Normally we'd call that like p.name=("Ian")
but we can leave off the parentheses and just use p.name = "Ian"
.
One final confusing bit: All Ruby methods automatically return the last statement of their body. This means we don't need to use the return keyword for simple cases like our name
method.
def name
@name # Return @name because it's the last statement in the method
end