Created
September 20, 2011 16:04
-
-
Save ngty/1229514 to your computer and use it in GitHub Desktop.
Module#attr_accessor & friends
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
# 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. |
U mean extra reference links ?
Yeah, like best tutorial of the attr_reader, because sometimes I may find misleading resources.
Agree.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
WoW, ruby tips lesson 1.
It's better to provide a link to read up about this :)