Skip to content

Instantly share code, notes, and snippets.

@hrs
Last active August 29, 2015 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hrs/e3f6f9891d31bedaf305 to your computer and use it in GitHub Desktop.
Save hrs/e3f6f9891d31bedaf305 to your computer and use it in GitHub Desktop.
Using attr_readers, attr_writers, and attr_accessors
# attr_reader/writers/accessors are handy shortcuts for creating
# getter and setter methods. That's all they're for.
# An attr_reader creates a getter method. For example, the following
# two classes have identical effects:
class NamedWombat
attr_reader :name
def initialize(name)
@name = name
end
end
class NamedWombat
def name
@name
end
def initialize(name)
@name = name
end
end
# In either case we can define a wombat and get its name.
elmer = NamedWombat.new("Elmer")
elmer.name # => "Elmer"
# An attr_writer creates a setter method. Using an attr_accessor is
# equivalent to using both an attr_reader and an attr_writer. So the
# following three classes have identical effects:
class RenamableWombat
attr_accessor :name
def initialize(name)
@name = name
end
end
class RenamableWombat
attr_reader :name
attr_writer :name
def initialize(name)
@name = name
end
end
class RenamableWombat
def name
@name
end
def name=(new_name)
@name = new_name
end
def initialize(name)
@name = name
end
end
# Any of those three definitions would let us define and acces a
# wombat as follows:
my_wombat = RenamableWombat.new("Elmer")
my_wombat.name # => "Elmer"
my_wombat.name = "Lucky Eddy"
my_wombat.name # => "Lucky Eddy"
# attr_readers, attr_writers, and attr_attributes can all be defined
# privately. So, for example, the following two class definitions are
# equivalent:
class AnonymousWombat
def initialize(name)
@name = name
end
private
attr_reader :name
end
class AnonymousWombat
def initialize(name)
@name = name
end
private
def name
@name
end
end
# When we try to call name on an AnonymousWombat, Ruby rightly
# complains that we're trying to call a private method:
secret_wombat = AnonymousWombat.new("Elmer")
secret_wombat.name # =>
# ~> -:103:in `<main>': private method `name' called for #<AnonymousWombat:0x007fe54186b1d0 @name="Elmer"> (NoMethodError)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment