Everything in Ruby is an object. You might have heard or read that before somewhere.
What this means for you is that you can do things like
1.to_s that you wouldn’t be able
to do in other languages because an integer is typically a
scalar data type. In Ruby
1 is an object.
Objects have attributes and methods. In other words, objects store information and can perform some behavior. An object is also known as an “instance” of a class definition. Consider the following class definition (or blueprint).
(irb) > class Car (irb) > def initialize(sound) (irb) > @sound = sound (irb) > end (irb) > (irb) > def honk (irb) > puts @sound (irb) > end (irb) > end
This class defines an instance method
honk. To invoke the
honk instance method we must first create an
instance of this class (hence the name “instance method”).
(irb) > mycar = Car.new("beep!") (irb) > mycar.honk beep! => nil
initialize method is a reserved method name in Ruby. When a class defines the method
initialize, those expressions are executed when an object is instantiated using the
new class method. It’s called a “class method” because you invoke it from the class name
not an instance of the class.
There is much to learn about Object Oriented Programming, but one of the most common expressions I see in Ruby (especially Rails) is the use of inheritance.
(irb) > class Racecar < Car (irb) > end (irb) > r = Racecar.new("beep beep") (irb) > r.honk beep beep => nil
< Car of the class definition tells Ruby that
Racecard is a subclass of
and all of its public and protected methods should be inherited.
If a subclass defines a method with the same name as its parent class, you can use the
super keyword to invoke the parent class method.
(irb) > class Racecar < Car (irb) > def initialize(sound, speed) (irb) > super(sound) (irb) > @speed = speed (irb) > end (irb) > end (irb) > r = Racecar.new("beep beep") (irb) > r.honk beep beep => nil
We didn’t do anything with the new attribute
@speed but this is an example of using
super to invoke the parent class’ method definiton.