Skip to content

Instantly share code, notes, and snippets.

@phuibonhoa
Last active August 29, 2015 14:05
Show Gist options
  • Save phuibonhoa/3ed6770aeb5c756088c2 to your computer and use it in GitHub Desktop.
Save phuibonhoa/3ed6770aeb5c756088c2 to your computer and use it in GitHub Desktop.
use attr_reader methods instead of @instance_variables internally within a class
# 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