liveBook · Manning

Send

As explained in The Well-Grounded Rubyist, Fourth Edition

send is a Ruby method, also available as __send__, that invokes a named method on an object and can bypass method visibility restrictions.

send invokes a named method on an object without using the dot operator. Because the method name can come from a variable or runtime input, it turns a message into data that Ruby can dispatch dynamically. section 2.3.3 section 8.2.3

Dispatching a ticket query

A ticket program can read a request such as "venue", check `ticket.respond_to?(request)`, and call `ticket.send(request)` instead of writing a separate conditional for every property. The check prevents unknown requests from being sent blindly. section 2.3.3

Use the related forms according to the method name and visibility you need:

  • `__send__` provides the same behavior with a name unlikely to collide with an application-defined `send` method. section 2.3.3
  • `public_send` restricts dispatch to public methods, whereas `send` can invoke private methods. section 2.3.3
  • Pass a symbol such as `:upcase`, or pass a string such as `"upcase"`; symbols can avoid conversion while Ruby locates the method. section 8.2.3
if ticket.respond_to?(request)      1
  puts ticket.send(request)
else
  puts "No such information available"
end

Inspect the guarded ticket-query pattern that combines dynamic input, respond_to?, and send. section 2.3.3

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Demonstrates syntax, runtime method-name arguments, visibility differences, naming conflicts, and a guarded input-driven pattern.
Examples
Uses ticket-property queries, `"abc".send(:upcase)`, and method names stored or normalized as symbols.
What it assumes
Assumes familiarity with Ruby objects, ordinary dot-based method calls, conditional checks, and basic symbols or strings.
What you can do after
Apply it to route runtime-selected method names while choosing `__send__` for collision avoidance and `public_send` for public-only access.
How it connects
Connects dynamic dispatch with objects, methods, respond_to?, symbols, private methods, and public_send.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.