Skip to content

Instantly share code, notes, and snippets.

@ngty
Created September 20, 2011 16:04
Show Gist options
  • Save ngty/1229514 to your computer and use it in GitHub Desktop.
Save ngty/1229514 to your computer and use it in GitHub Desktop.
Module#attr_accessor & friends
# Have u ever found urself doing this:
class Thing
def size=(size)
@size = size
end
def size
@size
end
end
# You can avoid doing the above by using Module#attr_accessor:
class Thing
attr_accessor :size
end
t = Thing.new
t.size = :xl
puts t.size # >> xl
# Module#attr_accessor is written in C, so definitely it is more
# performant. Let's say u want the writer to be accessible only
# within the instance itself, u can do the following:
class Thing
attr_accessor :size
private :size=
def cheat(size)
self.size = size
end
end
t = Thing.new
#puts t.size = :xl # >> NoMethodError
t.cheat(:xl)
puts t.size # >> xl
# Exercise: Try out Module#attr_reader & Module#attr_writer as well.
@ngty
Copy link
Author

ngty commented Sep 21, 2011

Agree.

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