This is the default behavior, albeit a confusing one (especially if you're used to other languages in the OOP region).
Instance variables in Ruby starts being available when it is assigned to and normally this happens in the initialize
method of your class.
class Person
def initialize(name)
@name = name
end
end
In your examples you're using attr_accessor
, this magical method produces a getter and a setter for the property name. A Person#name
and Person#name=
, method is created which overrides your "inline" instance variable (that's why your first example works and the second one doesn't).
So the proper way to write your expected behaviour would be with the use of a initialize
method.
class Person
def initialize(name)
@name = name
end
def greeting
"Hello, #{@name}"
end
end
Edit
After a bit of searching I found this awesome answer, all rep should go to that question.