我什么时候应该使用别名方法? -红宝石 [英] When should I use an Alias Method? - Ruby

查看:129
本文介绍了我什么时候应该使用别名方法? -红宝石的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已浏览并没有找到以下答案:

I've looked through and haven't seen an answer to:

您将使用别名方法吗?

class Vampire
 attr_reader :name, :thirsty

 alias_method :thirsty?, :thirsty
end

我会使用的唯一原因是能够使用我定义的任何方法使用问号吗?我相信您不能在实例变量中使用问号.

Is the only reason I would use one is to be able to use a question mark with whatever method I define? I believe you can't use question marks with instance variables.

推荐答案

我认为这是从我回答的较早的问题开始的,在这里我建议使用alias_method,因此我对此有一些补充说明.在这种情况下使用.

I think this is from an earlier question I responded to, where I proposed using alias_method, so I have a little bit of extra context into this to explain it's use in that context.

在代码段中,您有一些读取attr_reader :thirsty的代码,该代码基本上是同名实例(@thirsty)的实例变量的吸气剂

In your code snippet, you have a bit of code that reads attr_reader :thirsty that is basically a getter for an instance variable of the same name (@thirsty)

def thirsty
  @thirsty
end

在原始代码段中,您有一个断言:

In the original code snippet, you had an assertion that was:

refute vampire.thirsty?

您还拥有简单地为thirsty?方法返回true的代码,但断言失败.

You also had code that simply returned true for thirsty? method, which failed your assertion.

至少有两种方法可以修改代码,以使对thirsty?的调用有效并通过您的断言:

There are at least two ways you could have modified your code so that the call to thirsty? worked and your assertion passed:

创建一个调用thirsty读取器的方法,或访问@thirsty实例变量本身:

Create a method that calls the thirsty reader, or access the @thirsty instance variable itself:

def thirsty?
  thirsty # or @thirsty
end

另一种方法是使用alias_method,它在功能上与上述等效.它别名thirsty?thirsty,这是从@thirsty实例变量读取的attr_reader

The other way is to use alias_method, which is functionally equivalent to the above. It aliases thirsty? to thirsty which is an attr_reader which reads from the @thirsty instance variable

参考我给的另一个答案

您最好根本不使用attr_reader,而是按照Sergio在他的评论中指出的那样做:

You might be better off not using an attr_reader at all, instead just doing as Sergio noted in his comment:

class Vampire
  def initialize(name)
    @name = name
    @thirsty = true
  end

  def thirsty?
    @thirsty
  end

  def drink
    @thirsty = false
  end
end

这篇关于我什么时候应该使用别名方法? -红宝石的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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