使用发送方法和点方法的区别

时间:2021-01-24 22:32:11

The book The Well Grounded Rubyist states that you could use the send method as such to check if an object (ticket) responds to user input:

《可靠的Rubyist》一书指出,你可以使用发送方法来检查对象(票据)是否对用户输入作出响应:

if ticket.respond_to?(request) 
  puts ticket.send(request)
else
  puts "No such information available"
end  

What is the difference between the code above and writing:

上面的代码和写的代码有什么不同:

if ticket.respond_to?(request) 
  puts ticket.request
else
  puts "No such information available"
end  

If ticket responds to the user input, why not just call it directly using the dot notation?

如果ticket响应用户输入,为什么不直接使用点符号调用呢?

1 个解决方案

#1


7  

ticket.request sends the message request to the ticket object.

票。请求将消息请求发送到ticket对象。

ticket.send(request) sends whatever is contained in the variable request to the ticket object. So if you had written request = :clone before this, that line would be equivalent to ticket.clone.

发送(请求)将变量请求中包含的任何内容发送给票据对象。因此,如果您在此之前编写了request =:clone,这一行将等同于ticket.clone。

#1


7  

ticket.request sends the message request to the ticket object.

票。请求将消息请求发送到ticket对象。

ticket.send(request) sends whatever is contained in the variable request to the ticket object. So if you had written request = :clone before this, that line would be equivalent to ticket.clone.

发送(请求)将变量请求中包含的任何内容发送给票据对象。因此,如果您在此之前编写了request =:clone,这一行将等同于ticket.clone。