Chapter 3: Part 2

Like in other object-oriented languages, inheritance is how have one class take on the methods and attributes of another class. Inheritence is often said to express is-a relationships. Below

class Sedan < Car
end


In the above example we create a new class Sedan that inherits from the Car class from our previous examples. The < inheritence operator is another one of myriad beautifully simple syntaxes Ruby has to offer. Most languages require lots of cumbersome code to achieve things like inheritance. Often this is to maximize machine efficiency. Ruby uses a very different approach. Modern computers are lightyears ahead of where they were when other object-oriented languages like C++(1983), Python(1991), and Java(1995) were developed. Though Ruby was developed in 1995 as well, the intention was to create a language that, though less efficient than other languages, is fun to use. Today, the kinds of differences in efficiency between Ruby and other languages are nearly meaningless in real life usage since computers are so incredibly powerful.

In Ruby, modules are containers that hold methods and constants. Ruby is chock full of tools we want to use, but we don't want code littered all over our interpreter. So we store lots of tools in modules and only use them when we need to access their the constants or methods. Modules are like classes that don't have instances and don't have sub-modules (the way a class has subclasses). Modules even use the same naming convention as classes, upper CamelCase with no underscores. Take a look at the syntax:

module MyModule
  MY_CONSTANT = 0
end


In this example our module MyModule has a constant MY_CONSTANT. Constants are references to objects that don't change. Above we are referring to the 0 object. The constant syntax requires names in all caps with underscores if there are multiple words. Being the flexible language it is, Ruby does allow you to change the value of constants but it'll warn you.

module Action
  def whistle
    puts "Come forth! March to the Capitol!"
  end
end

class Mockingjay
  include Action
  attr_reader :color
  def initialize(district)
    @district = district
  end
end

katniss = Mockingjay.new(12)

katniss.whistle


Here we are able to borrow the .whistle method from the Action module for use in our Mockingjay class. See how we can call that method from any Mockingjay object we create. Pretty cool!

Ruby is really all about making the programmer's life easier. Mixins are a way of adding flexiblity while still having as many DRY pieces of code as we can. The benefits of the DRY life are many, not the least of which is, LESS CODE.