简体   繁体   中英

Ruby alias alias_method confusion

I have this piece of code here:

class MyFile
  attr_accessor :byte_content

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

On the class MyFile there is an alias_method , but I do not understand how this method is working. Does it change the way the getter and setter for :byte_content are called?

Also, what is the difference between this method and just using alias ? When should I one over the other?

Thanks in advance for your time!

This:

attr_accessor :byte_content

Essentially does:

def byte_content
  @byte_content
end 

def byte_content=(value)
  @byte_content = value
end

Then

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

will create copies of the byte_content and byte_content= methods with read and write as the new names . If you modify the byte_content or byte_content= methods after the aliasing, the read and write will remain unchanged.

So, the intention of the alias_method in the example appears to be to give the user a more " File -like" interface. Without the method aliases, you would use:

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

With the aliases, the user can use:

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

Which is quite similar to the methods of the standard library File class,

file = File.open('/tmp/foo.txt', 'w')
file.write('hello')
file.rewind
puts file.read

And this makes it possible to use instances of MyFile in place of real File instances in some very simple use-cases, also known as Duck-typing .

alias vs alias_method

The differences of alias and alias_method are described in the answers to this question , most imporantly:

  • you can override alias_method but not alias
  • alias_method is used with symbols as the method names, making it useful for dynamically created methods

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM