Bo G.
Bo G.

Reputation: 107

How does attr_accessor know that :player = @player?

Here's the code:

class Dungeon   
  attr_accessor :player 
    def initialize(player_name)   
    @player = Player.new(player_name)   
    end 
end

Now, if I write:

dungeon = Dungeon.new("Robert")
puts dungeon.player.name

it's obviously going to spit out Robert.

I'm a little new to Ruby, so forgive me if this question is obvious to you all. I'm struggling to wrap my head around it still. I am learning about "instance", "class", and global variables and my question is: How does Ruby know that :player in the code above refers to @player? Why isn't the code written, instead, :@player?

Does that make any sense?

Upvotes: 0

Views: 78

Answers (2)

SciPhi
SciPhi

Reputation: 2665

One thing that is easy to overlook when first learning Ruby is that the construct

attr_accessor :property_name

is just a shorter way of writing getter and setter methods for a class's instance variables:

# getter
def property_name
  @property_name
end

# setter
def property_name=( some_value )
  @property_name = some_value
end

It's basically an example of the "metaprogramming" support in Ruby, but it feels like something more mysterious.

Also, you do not have to use the symbol style, you could instead have:

attr_accessor "property_name"

The symbol version just "reads better" for most people.

Upvotes: 1

Logan Serman
Logan Serman

Reputation: 29880

attr_accessor is just a method that defines a public getter/setter. @player is the actual instance variable that stores values. The getter it generates is based on the symbol name, so :player creates these methods:

def player
  @player
end

def player=(player)
  @player = player
end

If you only want the getter you can use attr_reader. If you only want the setter you can use attr_writer. attr_accessor combines these two methods and gives you both methods.

Upvotes: 1

Related Questions