O'Reilly logo

Ruby Cookbook by Leonard Richardson, Lucas Carlson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

10.14. Aliasing Methods

Problem

You (or your users) frequently misremember the name of a method. To reduce the confusion, you want to make the same method accessible under multiple names.

Alternatively, you're about to redefine a method and you'd like to keep the old version available.

Solution

You can create alias methods manually, but in most cases, you should let the alias command do it for you. In this example, I define an InventoryItem class that includes a price method to calculate the price of an item in quantity. Since it's likely that someone might misremember the name of the price method as cost, I'll create an alias:

	class InventoryItem
	  attr_accessor :name, :unit_price

	  def initialize(name, unit_price)
	    @name, @unit_price = name, unit_price
	  end

	  def price(quantity=1)
	    @unit_price * quantity
	  end

	  #Make InventoryItem#cost an alias for InventoryItem#price
	  alias :cost :price
	
	  #The attr_accessor decorator created two methods called "unit_price" and
	  #"unit_price=". I'll create 
aliases for those methods as well.
	  alias :unit_cost :unit_price
	  alias :unit_cost= :unit_price=
	end

	bacon = InventoryItem.new("Chunky Bacon", 3.95)
	bacon.price(100)                                  # => 395.0
	bacon.cost(100)                                   # => 395.0

	bacon.unit_price                                  # => 3.95
	bacon.unit_cost                                   # => 3.95
	bacon.unit_cost = 3.99
	bacon.cost(100)                                   # => 399.0

Discussion

It's difficult to pick the perfect name for a method: you must find the word or short phrase that best conveys an operation on a data structure, possibly an abstract operation that has different "meanings" ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required