Last active
September 15, 2018 09:00
-
-
Save JamesMGreene/54d77bf9c786fb34b498 to your computer and use it in GitHub Desktop.
Ruby class methods vs. instance methods
This file contains hidden or 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
class Human | |
# Class method (a.k.a. static method) | |
def self.classification | |
'Mammal' | |
end | |
# Instance constructor | |
def initialize(first_name, last_name) | |
@my_first_name = first_name | |
@my_last_name = last_name | |
end | |
# Instance method | |
def full_name | |
"#{@my_first_name} #{@my_last_name}" | |
end | |
end |
This file contains hidden or 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
puts Human.classification # => 'Mammal' | |
puts Human.full_name # => NoMethodError: undefined method 'full_name' for Human:Class | |
# Create a new instance of the Human class | |
teresa = Human.new('Teresa', 'Nestle-Quik') | |
puts teresa.classification # => NoMethodError: undefined method 'classification' for #<Human:0x1e820> | |
puts teresa.full_name # => 'Teresa Nestle-Quik' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment