Skip to content

alias vs. alias_method #127

Description

@michaeledgar

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"

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions