Ruby Classes and Instances
March 16, 2016

What is a Class? What is an Instance?
In this blog post, we'll talk about Ruby classes and instances. Let's take a look at the above image. In Ruby, a class is a blueprint from which instances or objects are created. We can see a building is a class while the Empire State Building is an instance (object) created from building which makes sense because Empire State is a building right? The World Trade Center and Chrysler Building comes from the building class too because they are buildings as well.
Let's take a look at the dog example. A dog is a class and it creates Lassie, a famous dog and an instance of the dog class. If you want to know more about Lassie then check out Wikipedia. If you happen to have a dog at home, well your dog came from the dog class too. If instead you have a cat then it came from the cat class and not dog class.
class Puppy def initialize(name) @name = name end def wag_tail puts "#{@name} wags his tail!" end def puppy_dog_eyes puts "#{@name} looks at you with puppy dog eyes" end end ruby = Puppy.new("Ruby") ruby.wag_tail ruby.puppy_dog_eyes
Ruby Class Example
The above is an example of how a class looks like in Ruby. We created a class called Puppy and it has 3 methods,
basically behaviors or actions all instances of the Puppy class can use. Every class comes with an initialize
method which allows us to put default values into all new instances of the class. So when we
make a new Puppy instance, we have to initialize with a name because that's how we defined
the initialize method using def initialize(name)
. Let's say we want to
name our puppy "Ruby" so we would create a variable to save "Ruby" using ruby =
Puppy.new("Ruby")
Then we save the Puppy's name into an instance variable called @name
. We know
this is an instance variable because it has the @ character. Instance variables are variables that can be used
and reused throughout all methods of the class. Next we have the wag_tail method that outputs an action using
the name we intialized with. We can then call this method using the variable we created using
ruby.wag_tail
and we can call the last method using
ruby.puppy_dog_eyes
. Try these codes out on
repl.it and create more class methods for your
Puppy.
Classes and instances are great for organizing and reusing our codes. The methods we created in the Puppy class won't be accessible by the Kitten class or vice versa. And by making our Puppy class, we can make many puppy instances and all of them can use the methods we created in the Puppy class. Learn more about Ruby class here.