0
0
Rubyprogramming~3 mins

Why operators are methods in Ruby - The Real Reasons

Choose your learning style9 modes available
The Big Idea

What if the simple plus sign could do exactly what you want, even for your own objects?

The Scenario

Imagine you want to add two numbers in your program. You might write code like 5 + 3. But what if you want to add two special objects, like dates or custom shapes? Without a flexible way, you'd have to write separate functions for each type, making your code messy and hard to manage.

The Problem

Manually handling each operation for different types means writing lots of repetitive code. It's slow to write, easy to make mistakes, and hard to change later. Plus, you lose the natural feel of using simple symbols like + or - because you have to call special functions instead.

The Solution

Ruby treats operators like + and - as methods. This means you can define how these operators work for your own objects by writing methods with the operator's name. It keeps code clean, lets you reuse operators naturally, and makes your objects behave like built-in types.

Before vs After
Before
def add_numbers(a, b)
  a + b
end

add_numbers(5, 3)
After
class Point
  attr_accessor :x, :y

  def initialize(x, y)
    @x = x
    @y = y
  end

  def +(other)
    Point.new(x + other.x, y + other.y)
  end
end

p1 = Point.new(1, 2)
p2 = Point.new(3, 4)
p p1 + p2
What It Enables

This lets you use simple symbols like + to work naturally with your own objects, making your code easier to read and write.

Real Life Example

Think about a game where you add two positions on a map. By making + a method, you can just write pos1 + pos2 instead of calling a special function, making your code clear and intuitive.

Key Takeaways

Operators as methods let you customize behavior for your objects.

This approach keeps code clean and easy to understand.

You can use familiar symbols naturally with your own data types.