From: http://galeki.is-programmer.com/show/183.html
Like other oo languages, in ruby, object functions are completed by sending messages to objects, such as Str. upcase is the message that sends upcase to str. The vertex operator (.), it is used to send messages to objects. Str receives the messages and then executes the corresponding functions of the messages.
However, in some cases, we do not know which messages the object can respond to. For example, the following code produces an error:
- > OBJ = object. New
- > Obj. Talk
- Undefined method 'tal' for # <object: 0x12345678> (nomethoderror)
Because the OBJ object cannot respond to the talk message, if respond_to? This method can be used to determine whether an object can respond to a given message:
- OBJ = object. New
- If obj. respond_to? ("Talk ")
- OBJ. Talk
- Else
- Puts "sorry, object can't talk! "
- End
In this way, even if OBJ cannot respond to talk, it will not cause code errors to exit. We can also apply respond_to? Method, flexible control during program running based on object attributes.
And respond_to? Correspondingly, the send method is the same as the dot operator to send messages to objects, such as STR at the beginning of the article. upcase, which can be written as STR by sending. send ("upcase"), they implement the same functions, so why should we use send?
This is because the send message is variable when the program is running. We can dynamically send different messages to the object based on different inputs.
For example, in a book management system, each book has attributes such as author, publisher, date, and price. We need to query the attributes of a book based on user input. If you do not need to send, we need to test the input of the program one by one:
- Print "Search :"
- Request = gets. Chomp
- If request = "Writer"
- Puts book. Writer
- Elsif request = "Press"
- Puts book. Press
- Elseif request = "date"
- Puts book. Date
- ......
If the send method is used, it is much simpler:
- Request = gets. Chomp
- If book. respond_to? (Request)
- Puts book. Send (request)
- Else
- Puts "Input error"
- End
In this way, you do not need to test user input one by one, as long as the query object can correspond to this message, and then send the input directly to the object.
Through respond_to? And send. We can construct more flexible and stable programs.