Last active
December 29, 2015 20:28
-
-
Save Chryus/7723531 to your computer and use it in GitHub Desktop.
Example using attr_accessor to transform data (variables) in messages (methods).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Artist | |
#attr_accessor is ruby magic that transforms instance variables into reader & writer methods (see lines 14-22) | |
attr_accessor :name, :songs | |
ARTISTS = [] | |
def initialize | |
@name = name | |
@songs = [] | |
#for each instance of the class artist we instantiate(self), we push it into the ARTISTS array via the shovel method. | |
ARTISTS << self | |
end | |
#reader | |
def name | |
@name | |
end | |
#writer | |
def name=(name) | |
@name = name | |
end | |
end | |
artist = Artist.new("Miss Piggy", ["Heeeee-YAH!"]) | |
#by way of attr_accessor built in reader method, we can call name on an instance of the class artist to read the name. | |
puts artist.name | |
# => Miss Piggy | |
#likewise, via the attr_accessor's built in writer method, we can change artist's name at any time we want. | |
artist.name=("Prince") | |
puts artist.name | |
# => Prince | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment