Methods in Ruby are reusable blocks of code that perform specific tasks. They make your code modular, reusable, and easier to maintain.
What You’ll Learn
Table of Contents
1. What Are Methods?
A method in Ruby is a block of reusable code encapsulated under a name. You can call this name to execute the method and perform its task.
2. Defining Methods
Syntax
def method_name # Code to execute end
Example
def greet puts "Hello, Ruby!" end greet # Output: Hello, Ruby!
3. Calling Methods
Simply use the method name followed by parentheses (optional if no arguments).
def greet puts "Hello!" end greet # Output: Hello! greet() # Output: Hello!
4. Method Parameters
You can pass parameters to a method for dynamic behavior.
Example: Single Parameter
def greet(name) puts "Hello, #{name}!" end greet("Alice") # Output: Hello, Alice!
Example: Multiple Parameters
def add(a, b) puts a + b end add(5, 7) # Output: 12
5. Default Parameters
Default parameters provide a fallback value if no argument is passed.
Example
def greet(name = "Guest") puts "Hello, #{name}!" end greet # Output: Hello, Guest! greet("Bob") # Output: Hello, Bob!
6. Variable-Length Parameters
Use the splat operator (*) to accept a variable number of arguments.
Example
def sum(*numbers) puts numbers.sum end sum(1, 2, 3) # Output: 6 sum(10, 20, 30, 40) # Output: 100
7. Return Values
Methods can return values using the return keyword. If no return is specified, the last evaluated expression is returned.
Example: Implicit Return
def add(a, b) a + b end result = add(5, 3) puts result # Output: 8
Example: Explicit Return
def multiply(a, b) return a * b end puts multiply(4, 5) # Output: 20
8. Practical Examples
8.1 Method to Check Even or Odd
def even_or_odd(number) if number.even? "Even" else "Odd" end end puts even_or_odd(4) # Output: Even puts even_or_odd(7) # Output: Odd
8.2 Method to Find Maximum of Two Numbers
def max(a, b) a > b ? a : b end puts max(10, 20) # Output: 20
8.3 Method with Default and Optional Parameters
def greet_person(name = "Guest", age = nil) if age puts "Hello, #{name}! You are #{age} years old." else puts "Hello, #{name}!" end end greet_person # Output: Hello, Guest! greet_person("Alice") # Output: Hello, Alice! greet_person("Bob", 30) # Output: Hello, Bob! You are 30 years old.
8.4 Method to Calculate Factorial
def factorial(n) return 1 if n <= 1 n * factorial(n - 1) end puts factorial(5) # Output: 120
8.5 Method with Variable-Length Arguments
def concatenate(*words) words.join(" ") end puts concatenate("Hello", "world!") # Output: Hello world! puts concatenate("Ruby", "is", "fun") # Output: Ruby is fun
8.6 Method to Determine Prime Numbers
def prime?(n) return false if n <= 1 (2..Math.sqrt(n)).none? { |i| n % i == 0 } end puts prime?(7) # Output: true puts prime?(10) # Output: false
8.7 Method Overloading Using Default Parameters
Ruby does not support method overloading directly but you can mimic it using default or variable-length parameters.
def info(name, age = nil) if age puts "Name: #{name}, Age: #{age}" else puts "Name: #{name}" end end info("Alice") # Output: Name: Alice info("Bob", 30) # Output: Name: Bob, Age: 30
8.8 Lambda Functions
Lambdas are anonymous functions often used like methods.
say_hello = ->(name) { puts "Hello, #{name}!" } say_hello.call("Alice") # Output: Hello, Alice!
9. Best Practices for Ruby Methods
- Use Descriptive Names: Method names should clearly describe their purpose.
def calculate_area(radius)
- Keep Methods Short: Methods should perform one task only.
- Avoid Side Effects: Methods should not modify external variables unless necessary.
- Leverage Default Parameters: Use defaults for flexibility in method calls.
- Use return Only When Necessary: Leverage Ruby’s implicit return for cleaner code.
10. Summary
Key Concepts
- Methods encapsulate reusable code.
- Use parameters to pass data into methods.
- Default and variable-length parameters add flexibility.
- Return values can be explicit or implicit.
Examples in Context
Ruby methods allow you to write modular, reusable code, making your programs cleaner and easier to maintain