Classes & Objects
We describe pets by their attributes and behaviors.
All cats can be described by their name, color, and age. Those are called their attributes.
They can also meow, scratch, and sleep. Those are called their behaviors.
Basic class definition
class Cat
# Constructor method
def initialize(name, color, age)
@name = name # instance variable for name
@color = color # instance variable for color
@age = age # instance variable for age
end
end
new method.initialize method is a special method in Ruby that is called when a new instance of a class is created.Basic class definition
class Cat
# Constructor method
def initialize(name, color, age) # this is the method that is called on new
@name = name # instance variable for name
@color = color # instance variable for color
@age = age # instance variable for age
end
end
ferdinand = Cat.new('Ferdinand', 'tabby', 3)
milo = Cat.new('Milo', 'black and white striped', 12)
class Cat
# Constructor method
def initialize(name, color, age)
@name = name # instance variable for name
@color = color # instance variable for color
@age = age # instance variable for age
end
def say_hi
puts "Meow! My name is #{@name}, I am a #{@color} cat and I am #{@age} years old."
end
end
ferdinand = Cat.new('Ferdinand', 'tabby', 3)
ferdinand.say_hi
-> "Meow! My name is Ferdinand, I am a tabby cat and I am 3 years old."
class Cat
# Constructor method
def initialize(name, color, age)
@name = name # instance variable for name
@color = color # instance variable for color
@age = age # instance variable for age
end
def old?
if @age > 10
true
else
false
end
end
end
ferdinand = Cat.new('Ferdinand', 'tabby', 3)
ferdinand.old?
milo = Cat.new('Milo', 'black and white striped', 12)
milo.old?
-> false / true
cat_name = "Whiskers"
puts "The cat's name is #{cat_name}."
-> "The cat's name is Whiskers."
def print_cat_name
cat_name = "Whiskers"
puts cat_name
end
puts cat_name
-> "undefined local variable or method `cat_name' for main:Object (NameError)"
class Cat
def initialize(name)
@name = name
end
def print_name
puts "The cat's name is #{@name}."
end
end
cat = Cat.new("Whiskers")
cat.print_name
-> "The cat's name is Whiskers."
class MyClass
def my_method
@my_variable
end
end
my_object = MyClass.new
puts my_object.my_method
=> nil
class MyClass
def initialize
@my_variable = 12
end
def my_method
@my_variable
end
end
my_object = MyClass.new
puts my_object.my_method
=> 12