pickwick
pickwick

Reputation: 3154

Ruby alias_method or a new method?

Is there a reason why I should use alias_method like so:

alias_method :author, :name

instead of simply doing the following?

def author
self.name
end

Upvotes: 0

Views: 376

Answers (3)

Dan Grahn
Dan Grahn

Reputation: 9424

Writing the full method takes a substantial amount of time. In addition, alias_method can be used when you want to duplicate a more in depth method.

Finally, there is one subtlety.

class Foo
  def bar1
    "This is bar 1"
  end

  alias :bar2, :bar1

  def bar1
    "This is sparta!"
  end
end

puts Foo.new.bar1 # => "This is sparta!"
puts Foo.new.bar2 # => "This is bar 1"

The above shows that aliasing always points to the first method. This is important when considering inheritance.

See the Docs. They say it makes a copy of the old method.

Upvotes: 1

Ruy Diaz
Ruy Diaz

Reputation: 3122

alias_method will actually create a copy of the method for you. If you happened to later on redefine name with some new behaviour, author would still retain the original behaviour. This is useful if you want to preserve the original behaviour. See the docs for alias_method

Makes new_name a new copy of the method old_name. This can be used to retain access to methods that are overridden.

module Mod
  alias_method :orig_exit, :exit
  def exit(code=0)
    puts "Exiting with code #{code}"
    orig_exit(code)
  end
end
include Mod
exit(99) # => Exiting with code(99)

Upvotes: 1

Zippie
Zippie

Reputation: 6088

Because it is cleaner, and one of the thing Ruby enforces are conventions.

Also, if you would change the number of arguments to the name method, than you would have to change it on the author method, while with method_alias you wouldn't have to change it in multiple places.

Nevertheless, if you want to use the method you wrote and you're sure lets say the number of arguments won't change (which i'm sure it won't in your case), you can do that and it's not wrong, but also you don't need the self part, you can just write it like this:

def author
  name
end

Upvotes: 1

Related Questions