Does Ruby's define_method have special access to instance variables?

460 Views Asked by At

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”
1

There are 1 best solutions below

3
max pleaner On

It's about scope

  define_method(:output_name) do
    puts name
  end

The puts name part of this has instance scope.

Therefore it has access to instance methods such as the one generated by

attr_reader :name