ruby 是否有更简单的(一行)语法来为一个类方法设置别名?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15130998/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 05:47:18  来源:igfitidea点击:

Is there simpler (one-line) syntax to alias one class method?

ruby

提问by AJcodez

I know I can do the following, and it's just 3 lines:

我知道我可以执行以下操作,而且只有 3 行:

class << self
  alias :generate :new
end

But out of curiosity, is there a simpler way (without semicolons) like:

但出于好奇,是否有更简单的方法(没有分号),例如:

class_alias :generate, :new

回答by Konrad Reiche

Since Ruby 1.9 you can use the singleton_classmethod to access the singleton object of a class. This way you can also access the alias_methodmethod. The method itself is private so you need to invoke it with send. Here is your one liner:

从 Ruby 1.9 开始,您可以使用该singleton_class方法访问类的单例对象。这样您也可以访问该alias_method方法。该方法本身是私有的,因此您需要使用send. 这是你的一个班轮:

singleton_class.send(:alias_method, :generate, :new)

Keep in mind though, that aliaswill not work here.

但请记住,这alias在这里不起作用。

回答by Vijay Chouhan

I am pasting some alias method examples

我正在粘贴一些别名方法示例

class Test
  def simple_method
    puts "I am inside 'simple_method' method"
  end

  def parameter_instance_method(param1)
    puts param1
  end

  def self.class_simple_method
    puts "I am inside 'class_simple_method'"
  end

  def self.parameter_class_method(arg)
    puts arg
  end


  alias_method :simple_method_new, :simple_method

  alias_method :parameter_instance_method_new, :parameter_instance_method

  singleton_class.send(:alias_method, :class_simple_method_new, :class_simple_method)
  singleton_class.send(:alias_method, :parameter_class_method_new, :parameter_class_method)
end

Test.new.simple_method_new
Test.new.parameter_instance_method_new("I am parameter_instance_method")

Test.class_simple_method_new
Test.parameter_class_method_new(" I am parameter_class_method")

OUTPUT

输出

I am inside 'simple_method' method
I am parameter_instance_method
I am inside 'class_simple_method'
I am parameter_class_method

回答by Matt Sanders

I don't believe there is any class-specific version of alias. I usually use it as you have previously demonstrated.

我不相信alias. 我通常像您之前演示的那样使用它。

However you may want to investigate the differencebetween aliasand alias_method. This is one of those tricky areas of ruby that can be a bit counter-intuitive. In particular the behavior of aliaswith regard to descendants is probably not what you expect.

然而,你可能要探讨的差异之间aliasalias_method。这是 ruby​​ 的棘手领域之一,可能有点违反直觉。特别是alias关于后代的行为可能不是您所期望的。

Hope this helps!

希望这可以帮助!