Nuances of alias_method

R

Richard Leber

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
 
R

Robert Dober

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:

=A0class A
=A0 =A0def A.foo
=A0 =A0 =A0"Hello"
=A0 =A0end
=A0end

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

But this does:

=A0class A
=A0 =A0def A.foo
=A0 =A0 =A0"Hello"
=A0 =A0end
=A0end

=A0class << A
=A0 =A0alias_method :bar, :foo
=A0end

=A0A.foo # =3D> Hello
=A0A.bar # =3D> Hello
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


--=20
Learning without thought is labor lost; thought without learning is perilou=
s.=94
--- Confucius
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,226
Members
46,815
Latest member
treekmostly22

Latest Threads

Top