Learn Ruby - Modules, Classes, Inheritance

Question Click to View Answer

Create a Dog class that is initialized with a name.

class Dog
  def initialize(name)
    @name = name
  end
end

The initialize method is run whenever an object is instantiated. The @name instance variable is accessible to all instance methods in the Dog class.

Create a new instance of the Dog class.

a_dog = Dog.new("fido")

Objects are created with the new() method. new() is a class method of the Dog class.

Add a bark() instance method to the Dog class that returns "Ruff ruff".

class Dog  
  def initialize(name)
    @name = name
  end

  def bark()
    return("Ruff ruff")
  end
end

The bark() method can be called on any instances of the Dog class.

Create an instance of the Dog class and call the bark() method.

a_dog = Dog.new("fido")
a_dog.bark()

The syntax to call an instance method is the object, followed by dot, followed by the method name.

class Person
  def initialize(name, age)
    @name = name
    @age = age
  end
end

What does the following code return?

bob = Person.new("Bob", 22)
bob.speak()

A NoMethodError is raised because the Person class has not defined the speak() method.

class Insect
  def initialize(age_in_days)
    @age_in_days = age_in_days
  end
end

Add an instance method to the Insect class to calculate the age_in_years.

class Insect
  def initialize(age_in_days)
    @age_in_days = age_in_days
  end

  def age_in_years()
    return(@age_in_days.to_f / 365)
  end
end

We convert the @age_in_days instance variable to a floating point number before performing the division, so the division returns a floating point number, not a rounded integer.

class Dog
  def speak()
    return("woof woof")
  end
end

What does the following code return? ruby Dog.speak()

This raises an error as speak() is an instance method. To call the speak() method, we must first create an instance of the Dog class:

d = Dog.new()
d.speak()

Create a Lamp class with a class method called about_me that returns the String "We brighten up people's lives".

class Lamp
  def self.about_me()
    return("We brighten up people's lives")
  end
end

OR

class Lamp
  def Lamp.about_me()
    return("We brighten up people's lives")
  end
end

The about_me() method can be called directly on the Lamp class:

Lamp.about_me()
class WaterBottle
  def initialize(size)
    @size = size
  end
end

Add a method to the WaterBottle class that returns the size of the WaterBottle and demonstrate how this method can be used.

class WaterBottle
  def initialize(size)
    @size = size
  end

  def size()
    return(@size)
  end
end

klean_kanteen = WaterBottle.new(24)
klean_kanteen.size()

Create a Person class that is initialized with an age and create an age=() method that can be used to update the @age instance variable. Also include an age method that returns the value of the @age instance variable. Demonstrate how the methods can be used.

class Person
  def initialize(age)
    @age = age
  end

  def age=(new_age)
    @age = new_age
  end

  def age()
    return(@age)
  end
end


p = Person.new(24)
p.age  # returns 24
p.age=(42)  # update the @age instance variable
p.age  # now returns 42

Modules define methods that can be added to classes. Modules are useful for organizing code and for code that can be reused in multiple classes. Unlike classes, Modules cannot be instantiated (i.e. Modules cannot be used to create objects).

module Clueless
  def funny()
    return("AS IF?!")
  end
end

class Actress
  include Clueless
end

What does this code return?
alicia = Actress.new
alicia.funny()
"AS IF?!"

The funny() method is defined in the Clueless module. When the Clueless module is included in the Actress class, all the methods defined in the Clueless module are made accessible to the Actress class.

module HappyHappy
  def say_something()
    return("Happy happy, joy joy")
  end
end

class Person
  include HappyHappy
end

class Alien
  include HappyHappy
end

Demonstrate that instances of the Person class and instances of the Alien class can use the say_something() method.

p = Person.new()
p.say_something() # returns "Happy happy, joy joy"
a = Alien.new()
a.say_something() # returns "Happy happy, joy joy"

Create a module called MathHelper with a method multiply_by_two() that takes a number as an argument and multiplies it by two. Create a class called Homework and demonstrate how multiply_by_two() can be used.

module MathHelper
  def multiply_by_two(number)
    return(number * 2)
  end
end

class Homework
  include MathHelper
end

my_homework = Homework.new
my_homework.multiply_by_two(4)

Inheritance is a way for classes to access all the methods from a parent class. Inheritance is a great way for a class to get all the methods from a parent class and add some extra ones. In the following example, the Dog class inherits from the Mammal class.

class Mammal
  def heartbeat?
    true
  end
end

class Dog < Mammal
end

Demonstrate that instances of the Dog class have access to the heartbeat? method.

dog = Dog.new()
dog.heartbeat?  # this works
dog.methods().include?(:heartbeat?)  # returns true

The ancestors() class method demonstrates all the classes that a class inherits from. Show all the classes that the Array class inherits from.

Array.ancestors()

Array.ancestors() returns the following array: [Array, Enumerable, Object, Kernel, BasicObject]. In this list, Array, Object, and BasicObject are classes. Array inherits from Object and Object inherits from BasicObject. Enumerable and Kernel are modules. The Enumerable module is included in the Array class and the Kernel module is mixed-in to the Object class (mixed-in is another way of saying that a module is included in a class).

class Box
end

my_box = Box.new

Explain how my_box.methods().count() returns a number greater than 50, even though no methods are defined in the Box class.

The Box class inherits from the Object class, which gives the Box class all the methods from the object class. For example, the methods() method is not defined in my_box, but the methods() method is in the Object class, so my_box.methods() is valid.

Inheritance is important and there is a lot more to say, but this can wait until you are more familiar with object oriented programming. Focus on classes and modules first and then learn more about inheritance.

Create a BaseballPlayer class that is initialized with hits, walks, and at_bats. Add a batting_average() method that returns hits divided by at_bats as a floating point number. Add an on_base_percentage() method that returns (hits + walks) divided by at_bats as a floating point number. Demonstrate how the batting_average() and on_base_percentage() methods can be used.

class BaseballPlayer
  def initialize(hits, walks, at_bats)
    @hits = hits
    @walks = walks
    @at_bats = at_bats
  end

  def batting_average()
    return(@hits.to_f / @at_bats)
  end

  def on_base_percentage()
    return((@hits + @walks).to_f / @at_bats)
  end
end


barry_bonds = BaseballPlayer.new(330, 110, 1125)
barry_bonds.batting_average()
barry_bonds.on_base_percentage()

Create a Person class that is initialized with a first_name and last_name. Create first_name() and last_name() methods that return the values of the corresponding instance variables. Create a full_name() method that concatenates the first_name and last_name in a single string.

class Person
  def initialize(first_name, last_name)
    @first_name = first_name
    @last_name = last_name
  end

  def first_name()
    return(@first_name)
  end

  def last_name()
    return(@last_name)
  end

  def full_name()
    return("#{first_name} #{last_name}")
  end
end

bob = Person.new("Bob", "Lob")
bob.full_name()

Create a module called MathHelpers with the exponent() method that takes a two numbers as arguments and raises the first number to the power of the second number. Create a class called Calculator with a method called square_root() that takes the square root of the number (raises it to the power of 0.5). The square_root() method should use the exponent() method.

module MathHelpers
  def exponent(number, exponent)
    return(number ** exponent)
  end
end

class Calculator
  include MathHelpers

  def square_root(number)
    return(exponent(number, 0.5))
  end
end

c = Calculator.new
c.square_root(4)
c.square_root(5)