Skip to content

Instantly share code, notes, and snippets.

@irmiller22
Created July 18, 2014 15:30
Show Gist options
  • Save irmiller22/340b809e183656d1a87f to your computer and use it in GitHub Desktop.
Save irmiller22/340b809e183656d1a87f to your computer and use it in GitHub Desktop.

This is in response to your question about initializing a new instance of a class, and correspondingly passing in parameters that are initialized with the class. Let's take an example below:

class Person
  def initialize(name)
    @name = name
  end
end

When you initialize a new Person, as in Person.new("John"), it will create a new Person instance that has an instance variable @name that is set equal to the string that was passed into initialize as a parameter ("John"). However, you are not able to access the @name instance variable because you do not have a getter or a setter method, and it is simply a value that was instantiated with the new Person instance (this is related to attr_accessor/attr_writer/attr_reader, which I will get to in a moment).

Attr_writer is a setter method. This is what enables you to set a value to an object attribute. For example:

class Person
  def name=(value)
    @name = name
  end
end

This is the same thing as:

class Person
  attr_writer :name
end

This will enable you to do the following: ( person = Person.new, person.name = "John" ). Now you are able to store a string into the name=(value) method. However, you cannot access that "John" string by calling person.name, because you have not defined a getter method. If you try to call name on person (person.name), it will simply return nil.

Attr_reader is a getter method. This is what enables you to access an attribute that you have defined in a setter method. For example:

class Person
  def name
    @name = name
  end
end

This is the same thing as:

class Person
  attr_reader :name
end

Assuming that you have a setter method in place for the person instance mentioned earlier, the getter method will then enable you to do the following: ( person.name will now return the string "John", whereas before it would return nil ). Now you are able to retrieve the name attribute from the person instance.

Attr_accessor is simply the combination of both attr_reader and attr_writer. Does this make more sense? Let me know if that's helpful.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment