Calling Methods Dynamically
The Object#send method lets you tell any object to invoke a method by name. The first argument is a symbol or a string representing the name, and any remaining arguments are passed along to the method of that name. Let’s have a look at the following code:
| "John Coltrane".send(:length) # => 13 |
| "Miles Davis".send("sub", /iles/, '.') # => "M. Davis" |
There are two twists to send. First, your class might define its own send method if it wanted to send something somewhere. Ruby provides the __send__ method, defined in BasicObject, which is identical to send and is meant to be used in cases where send might have been overwritten .
Second, the send method doesn’t enforce method access, meaning that ...
Get Programming Ruby 3.3 now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.