Ruby:
Organizing code into functions
How to:
Imagine you’re writing a quick script to greet users:
def greet(name)
"Hello, #{name}!"
end
puts greet("Alice") # Output: Hello, Alice!
puts greet("Bob") # Output: Hello, Bob!
Or maybe you’re calculating the area of a circle:
def circle_area(radius)
Math::PI * radius ** 2
end
puts circle_area(5) # Output: 78.53981633974483
Neater and easier to handle, right?
Deep Dive
The concept of functions, also known as methods in Ruby, isn’t new—it’s as old as programming itself. Circling back to the 1950s, subroutines, as they were known, were introduced to reduce redundancy.
Alternatives? Sure, you’ve got inline code, you could go OOP with classes and objects, or even functional with lambdas and procs. But functions are the bread and butter of orderly code. Want performance? Local variables in functions are fast and functions can return values immediately with return
.
Implementation-wise, you can define a function with def
and end it with end
. You can set default parameters, use splat operators for variadic functions, and more. Functions can be as simple or complex as your heart desires.