wawa
wawa

Reputation: 11

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

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”

Upvotes: 1

Views: 521

Answers (1)

max pleaner
max pleaner

Reputation: 26788

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

Upvotes: 2

Related Questions