# Nuances of alias\_method

**URL:** <https://rubytalk.org/t/nuances-of-alias-method/58119>\
**Category:** ruby-talk\
**Created:** [12 April 2010 17:08 UTC](https://rubytalk.org/t/nuances-of-alias-method/58119 "2010-04-12T17:08:35Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Richard\_Leber](https://avatars.discourse-cdn.com/v4/letter/r/59ef9b/32.png) [@Richard\_Leber](https://rubytalk.org/u/Richard_Leber)\
**Post date:** [12 April 2010 17:08 UTC](https://rubytalk.org/t/nuances-of-alias-method/58119/1 "2010-04-12T17:08:35Z")

</div>

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:

&nbsp;&nbsp;class A  
&nbsp;&nbsp;&nbsp;&nbsp;def A.foo  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"Hello"  
&nbsp;&nbsp;&nbsp;&nbsp;end  
&nbsp;&nbsp;end

&nbsp;&nbsp;A.send(:alias\_method, :bar, :foo) # =\> NameError: undefined method  
`foo' for class `A'

But this does:

&nbsp;&nbsp;class A  
&nbsp;&nbsp;&nbsp;&nbsp;def A.foo  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"Hello"  
&nbsp;&nbsp;&nbsp;&nbsp;end  
&nbsp;&nbsp;end

&nbsp;&nbsp;class \<\< A  
&nbsp;&nbsp;&nbsp;&nbsp;alias\_method :bar, :foo  
&nbsp;&nbsp;end

&nbsp;&nbsp;A.foo # =\> Hello  
&nbsp;&nbsp;A.bar # =\> Hello

> **···**
>
> --  
> Posted via [http://www.ruby-forum.com/](http://www.ruby-forum.com/).

---

<div class="post-metadata">

**Author:** ![Forum](https://avatars.discourse-cdn.com/v4/letter/f/43a26b/32.png) [@Forum](https://rubytalk.org/u/Forum)\
**Post date:** [12 April 2010 17:41 UTC](https://rubytalk.org/t/nuances-of-alias-method/58119/2 "2010-04-12T17:41:12Z")

</div>

> 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/\](http://www.ruby-forum.com/%5C).

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  
&nbsp;&nbsp;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  
&nbsp;&nbsp;alias\_

or  
class A  
&nbsp;&nbsp;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
