0
0
Rubyprogramming~3 mins

Why Send for calling methods dynamically in Ruby? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could call any method just by its name, without writing endless if-else statements?

The Scenario

Imagine you have a program that needs to call different methods based on user input or some changing conditions. You try to write separate code for each method call manually.

The Problem

This manual way means writing many if-else or case statements. It gets long, hard to read, and easy to make mistakes. Adding new methods means changing lots of code.

The Solution

Using send lets you call any method by its name stored in a variable. This means one simple line can replace many if-else checks, making your code cleaner and easier to update.

Before vs After
Before
if action == 'start'
  start
elsif action == 'stop'
  stop
end
After
send(action)
What It Enables

You can write flexible programs that decide what to do at runtime without messy conditionals.

Real Life Example

A game where player commands like 'jump', 'run', or 'attack' are typed, and the program calls the matching method dynamically.

Key Takeaways

Manual method calls need many condition checks.

send calls methods by name stored in variables.

This makes code shorter, cleaner, and easier to change.