I am learning Ruby and have stumbled upon some code similar to the one below, which shows the difference between instance variables and class instance variables. I've tested it in my console and it works like described (outputs "John"). What I don't understand is how define_method accesses the @name instance variable without preceding name with a @? Does it have a special capability that allows it to do so?
class User
attr_reader :name
def self.name
"User"
end
def initialize(name)
@name = name
end
define_method(:output_name) do
puts name
end
end
user1 = User.new("John")
user1.output_name #=> “John”
It's about scope
The
puts namepart of this has instance scope.Therefore it has access to instance methods such as the one generated by