runpaint / read-ruby

Free ebook about Ruby 1.9
http://ruby.runpaint.org/
148 stars 28 forks source link

alias vs. alias_method #127

Open michaeledgar opened 13 years ago

michaeledgar commented 13 years ago

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"