Ruby别名alias_method的困惑

时间:2019-01-02 12:20:40

标签: ruby

我在这里有这段代码:

class MyFile
  attr_accessor :byte_content

  alias_method :read,  :byte_content
  alias_method :write, :byte_content=
end

在类MyFile上有一个alias_method,但我不了解此方法的工作方式。会改变:byte_content的getter和setter的调用方式吗?

此外,此方法与仅使用alias有什么区别?我什么时候应该一个接一个?

提前感谢您的时间!

1 个答案:

答案 0 :(得分:3)

此:

attr_accessor :byte_content

本质上是:

def byte_content
  @byte_content
end 

def byte_content=(value)
  @byte_content = value
end

然后

alias_method :read, :byte_content
alias_method :write, :byte_content=

将使用byte_contentbyte_content=作为新名称创建readwrite方法的副本。如果在别名之后修改byte_contentbyte_content=方法,则readwrite将保持不变。

因此,该示例中alias_method的意图似乎是为用户提供一个更类似于“ File”的界面。如果没有方法别名,则可以使用:

file = MyFile.new
file.byte_content = "abcd"
puts file.byte_content

使用别名,用户可以使用:

file = MyFile.new
file.write("abcd")
file.read

与标准库File

的方法非常相似
file = File.open('/tmp/foo.txt', 'w')
file.write('hello')
file.rewind
puts file.read

在某些非常简单的用例(也称为Duck-typing)中,这可以使用MyFile的实例代替实际的File实例。

aliasalias_method

this question的答案中最重要地描述了aliasalias_method的区别:

  • 您可以覆盖alias_method,但不能覆盖alias
  • alias_method与符号一起用作方法名称,使其对于动态创建的方法很有用