Alias and inheritance

11 views

What is the return value of the following Ruby code?

class Device
  def description
    'I\'m a device'
  end

  def self.alias_description
    alias describe description
  end
end

class Microwave < Device
  def description
    'I\' a microwave'
  end

  alias_description
end

m = Microwave.new
p m.description # => "I'm a microwave"

p m.describe # => ???

The correct answer is

"I'm a device"

"I'm a microwave"

Unlock Your Ruby Potential

Subscribe to RubyCademy and get free access to all our courses, plus hundreds of fun Ruby cards, quizzes, guides, and tutorials!

Explanation

The alias keyword

Now let’s see what happens with the alias keyword in Device

class Device
  def description
    'I\'m a device'
  end

  def self.alias_description
    alias describe description
  end
end

class Microwave < Device
  def description
    'I\' a microwave'
  end

  alias_description
end

m = Microwave.new

p m.description # => "I'm a microwave"
p m.describe    # => "I'm a device"

Here we can see that the call to alias within Device.alias_description sets the describe alias on the Device#description method and not on the Microwave#description one.

Module#alias_method

The Module#alias_method acts differently than the alias keyword on one specific point: the scope.

Let’s have a look at this example

class Device
  def description
    'I\'m a device'
  end

  def self.alias_description
    alias_method :describe, :description
  end
end

class Microwave < Device
  def description
    'I\' a microwave'
  end

  alias_description
end

m = Microwave.new

p m.description  # => "I'm a microwave"
p m.describe     # => "I'm a microwave"

Here we can see that the call to alias_method within the Device.alias_description method defines the describe alias on the Microwave#description method and not on Device#description.

Unlock Your Ruby Potential

Subscribe to RubyCademy and get free access to all our courses, plus hundreds of fun Ruby cards, quizzes, guides, and tutorials!

RubyCademy ©