0
0
Rubyprogramming~3 mins

Why Pure functions concept in Ruby? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if your code could be as predictable and reliable as a simple math problem?

The Scenario

Imagine you have a recipe book where each recipe changes ingredients randomly every time you cook. You try to follow the recipe, but the results are never the same. This is like writing code where functions change things outside themselves or depend on hidden information.

The Problem

When functions depend on or change things outside their own work, it becomes hard to predict what will happen. Bugs hide easily, and fixing one problem might cause another. It's like trying to fix a leaking pipe but water keeps flowing from unknown places.

The Solution

Pure functions always give the same output for the same input and never change anything outside themselves. This makes your code like a reliable recipe: you know exactly what to expect every time you run it. It's easier to test, understand, and fix.

Before vs After
Before
def add_to_list(item, list)
  list << item
  return list
end
After
def add_to_list(item, list)
  list + [item]
end
What It Enables

Pure functions let you build programs that are easier to trust, test, and change without unexpected surprises.

Real Life Example

Think of a calculator app: pressing 2 + 3 always shows 5, no matter what happened before. Pure functions help make that consistency happen in code.

Key Takeaways

Pure functions always return the same result for the same input.

They do not change anything outside themselves.

This makes code easier to understand and debug.