Last active
August 29, 2015 14:05
-
-
Save phuibonhoa/3ed6770aeb5c756088c2 to your computer and use it in GitHub Desktop.
use attr_reader methods instead of @instance_variables internally within a class
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
# attr_reader methods | |
# √ 1 common way to access attribute value | |
# √ Easier to refactor into a calculated/facade attribute | |
# attr_reader methods | |
class Person | |
attr_reader :name, :date_of_birth | |
def initialize(name:, date_of_birth:) | |
@name = name | |
@date_of_birth = date_of_birth | |
end | |
def greet | |
puts "Hi, my name is #{name}" | |
end | |
def age | |
Time.now.year - date_of_birth.year | |
end | |
end | |
# instance vars | |
class Person | |
attr_reader :name, :date_of_birth | |
def initialize(name:, date_of_birth:) | |
@name = name | |
@date_of_birth = date_of_birth | |
end | |
def greet | |
puts "Hi, my name is #{@name}" | |
end | |
def age | |
Time.now.year - @date_of_birth.year | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment