read-ruby icon indicating copy to clipboard operation
read-ruby copied to clipboard

alias vs. alias_method

Open michaeledgar opened this issue 14 years ago • 0 comments

In section VII.L., aliases, one thing is not mentioned that is a crucial difference between alias vs. alias_method: how they resolve the "source" method. In investigating the difference myself I came across this ruby-talk thread that illustrates it well; I'll copy/paste the relevant code sample. The long and short is that executing alias looks at the value of self lexically where the alias keyword lies, whereas executing alias_method uses the runtime value of self, which may be a subclass of where the call is lexically located.

class A
  def self.swap
    alias bar foo
  end
  def foo; "A foo"; end
end
class B < A
  def foo; "B foo"; end
  swap
end
B.new.bar
# => "A foo"

class Y
  def self.swap
    alias_method :bar, :foo
  end
  def foo; "Y foo"; end
end
class Z < Y
  def foo; "Z foo"; end
  swap
end
Z.new.bar
# => "Z foo"

michaeledgar avatar Feb 19 '11 21:02 michaeledgar