Nuances of alias_method

I am stumbling around some of the nuances of Ruby classes, especially in
regard to alias_method. Specifically, can someone explain to me why this
doesn't work:

  class A
    def A.foo
      "Hello"
    end
  end

  A.send(:alias_method, :bar, :foo) # => NameError: undefined method
`foo' for class `A'

But this does:

  class A
    def A.foo
      "Hello"
    end
  end

  class << A
    alias_method :bar, :foo
  end

  A.foo # => Hello
  A.bar # => Hello

···

--
Posted via http://www.ruby-forum.com/.

I am stumbling around some of the nuances of Ruby classes, especially in
regard to alias_method. Specifically, can someone explain to me why this
doesn't work:

class A
def A.foo
"Hello"
end
end

A.send(:alias_method, :bar, :foo) # => NameError: undefined method
`foo' for class `A'

But this does:

class A
def A.foo
"Hello"
end
end

class << A
alias_method :bar, :foo
end

A.foo # => Hello
A.bar # => Hello
--
Posted via http://www.ruby-forum.com/\.

Well alias_method aliases instance methods, as foo is not an instance
method of class A it cannot be aliased there. But as foo is an
instance method of the singleton class of A (class << A) it can be
aliased there.
IOW
class A
  def foo; 42 end
end
now foo is an instance method of A and not of (class << A) and thus
your A.send...
would work, as would
A.module_eval do
  alias_

or
class A
  alias_...
end

HTH
Robert

···

On Mon, Apr 12, 2010 at 7:08 PM, Richard Leber <rleber@mindspring.com> wrote:

--
Learning without thought is labor lost; thought without learning is perilous.”
--- Confucius