Skip to content

Instantly share code, notes, and snippets.

@JamesMGreene
Last active September 15, 2018 09:00
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JamesMGreene/54d77bf9c786fb34b498 to your computer and use it in GitHub Desktop.
Save JamesMGreene/54d77bf9c786fb34b498 to your computer and use it in GitHub Desktop.
Ruby class methods vs. instance methods
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
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