我应该使用alias还是alias_method? [英] Should I use alias or alias_method?

查看:168
本文介绍了我应该使用alias还是alias_method?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 alias alias_method 上找到了一篇博客文章。如该博客文章中给出的示例所示,我只想在同一个类中为另一个方法别名。我应该使用哪个?我总是看到使用 alias ,但是有人告诉我 alias_method 更好。

I found a blog post on alias vs. alias_method. As shown in the example given in that blog post, I simply want to alias a method to another within the same class. Which should I use? I always see alias used, but someone told me alias_method is better.

别名的使用

class User

  def full_name
    puts "Johnnie Walker"
  end

  alias name full_name
end

User.new.name #=>Johnnie Walker

alias_method的用法

class User

  def full_name
    puts "Johnnie Walker"
  end

  alias_method :name, :full_name
end

User.new.name #=>Johnnie Walker

此处的博客文章链接

推荐答案

alias_method 可以根据需要进行重新定义。 (在 Module 类中定义。)

alias_method can be redefined if need be. (it's defined in the Module class.)

别名的行为根据其范围而变化,并且有时可能是不可预测的。

alias's behavior changes depending on its scope and can be quite unpredictable at times.

判决:使用 alias_method -

用法:

def foo
  "foo"
end

alias_method :baz, :foo

这篇关于我应该使用alias还是alias_method?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆