In Ruby, inside a class\'s instance method, we use a getter by
foo
and we use a setter by
self.foo = something
Since local scope takes precedence, when you say foo = something
, a local variable foo
will be created and assigned the contents of something
.
The reason you can write foo
in order to use the getter is because Ruby will move up in scope when it can't find a variable with that name and it will eventually find the method.
If there is a local variable with the same name as the getter method, Ruby will use its value instead:
class Foo
attr_accessor :foo
def initialize
@foo = :one
end
def f
foo = :two
foo
end
end
Foo.new.f
# => :two
In order to make it clear that you want to access the setter, you must write self.foo = something
. That will tell Ruby you want to execute the foo=
method on the self
object with something
as parameter.