4

While learning ruby with tutorial on rubylearning i got to 'using alias' part of it. I cant understand what is the difference between using alias like in example:

def oldmtd  
  "old method"  
end  
alias newmtd oldmtd  
def oldmtd  
  "old improved method"  
end  
puts oldmtd  
puts newmtd

with output

old improved method
old method

and just assigning a new variable to this function, like:

def oldmtd  
  "old method"  
end  
newmtd = oldmtd  
def oldmtd  
  "old improved method"  
end  
puts oldmtd  
puts newmtd

with the same output:

old improved method
old method

Please, tell me what is actual difference and when it is correct to use 'alias'?

Pavel Kaigorodov
  • 322
  • 1
  • 2
  • 11
  • Add a required argument to the method and you'll notice the difference. eg. `def oldmtd(value); "old method with value: #{value}"; end` (replace the semicolons with newline characters). – 3limin4t0r Nov 20 '19 at 16:27
  • 1
    Also note that your example doesn't work at all if you do it inside a class with instance methods. They only appear equivalent in this case because you're using global functions – Max Nov 20 '19 at 16:56

2 Answers2

7

With newmtd = oldmtd you are not assigning a new variable to a function; you are assigning a variable to the result of a function, that is, a string. In Python terms: newmtd = oldmtd()

3limin4t0r
  • 19,353
  • 2
  • 31
  • 52
steenslag
  • 79,051
  • 16
  • 138
  • 171
1

Alias allows you to call an object with a different name. When you do variable assignment, you will assign it the value of whatever is returned by the right side of the = operator.

When you redefine the original method, you also redefine the aliased method because it still calls the original method for which it has been aliased.

However if you are aliasing a method, you probably want to use alias_method instead. See this question for more on this.

As for when or why to use alias, see answers to this question.

lacostenycoder
  • 10,623
  • 4
  • 31
  • 48
  • 1
    `alias` and `alias_method` have different use-cases. You want to use `alias` to statically alias methods and `alias_method` to dynamically alias methods. An advantage of `alias` is that it's picked up by RDoc, while `alias_method` isn't. Check out the Ruby style guide. https://github.com/rubocop-hq/ruby-style-guide#alias-method-lexically – 3limin4t0r Nov 20 '19 at 16:37
  • pretty sure RDoc can handle non-variable `alias_method` calls – cremno Nov 20 '19 at 16:46