0
0
Rubyprogramming~5 mins

Pure functions concept in Ruby

Choose your learning style9 modes available
Introduction

Pure functions always give the same result for the same inputs and do not change anything outside themselves. This makes programs easier to understand and test.

When you want to write code that is easy to test and debug.
When you want to avoid unexpected changes in your program.
When you want to write functions that are predictable and reliable.
When you want to reuse code without side effects.
When you want to make your program easier to understand by others.
Syntax
Ruby
def function_name(parameters)
  # calculate and return a value
end
A pure function must not change any variables or data outside itself.
It should only use its input parameters and return a result.
Examples
This function adds two numbers and returns the result. It does not change anything else.
Ruby
def add(a, b)
  a + b
end
This function returns the square of a number. It always returns the same output for the same input.
Ruby
def square(x)
  x * x
end
This function returns a greeting message without changing anything outside.
Ruby
def greet(name)
  "Hello, #{name}!"
end
Sample Program

This program defines a pure function multiply that returns the product of two numbers. It then calls the function and prints the result.

Ruby
def multiply(a, b)
  a * b
end

result = multiply(4, 5)
puts "The result is: #{result}"
OutputSuccess
Important Notes

Pure functions help avoid bugs caused by unexpected changes in data.

They make your code easier to test because you only check inputs and outputs.

Try to keep functions pure whenever possible for clearer and safer code.

Summary

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

They do not change anything outside themselves (no side effects).

Using pure functions makes your code easier to understand and test.