In Ruby, methods are a way to encapsulate reusable code. They allow you to define a set of instructions that can be called upon multiple times throughout your program. This not only makes your code more organized but also more readable and maintainable.

Key Concepts

  1. Defining a Method
  2. Calling a Method
  3. Method Parameters
  4. Return Values
  5. Default Parameters
  6. Variable Number of Arguments
  7. Method Overloading
  8. Scope and Visibility

  1. Defining a Method

To define a method in Ruby, you use the def keyword followed by the method name and an optional list of parameters. The method body contains the code to be executed, and the method definition is closed with the end keyword.

def greet
  puts "Hello, world!"
end

Explanation:

  • def greet: This line starts the method definition with the name greet.
  • puts "Hello, world!": This is the body of the method, which prints "Hello, world!" to the console.
  • end: This line ends the method definition.

  1. Calling a Method

To call a method, simply use its name followed by parentheses. If the method does not take any parameters, the parentheses are optional.

greet
# Output: Hello, world!

  1. Method Parameters

Methods can accept parameters, which are specified within parentheses after the method name. These parameters act as local variables within the method.

def greet(name)
  puts "Hello, #{name}!"
end

greet("Alice")
# Output: Hello, Alice!

Explanation:

  • def greet(name): The method greet now takes one parameter, name.
  • puts "Hello, #{name}!": The method prints a greeting that includes the value of name.

  1. Return Values

By default, a Ruby method returns the value of the last evaluated expression. You can also use the return keyword to explicitly specify the return value.

def add(a, b)
  return a + b
end

result = add(2, 3)
puts result
# Output: 5

Explanation:

  • def add(a, b): The method add takes two parameters, a and b.
  • return a + b: The method returns the sum of a and b.
  • result = add(2, 3): The method is called with arguments 2 and 3, and the result is stored in the variable result.

  1. Default Parameters

You can provide default values for parameters. If no argument is passed for a parameter with a default value, the default value is used.

def greet(name = "world")
  puts "Hello, #{name}!"
end

greet
# Output: Hello, world!

greet("Alice")
# Output: Hello, Alice!

Explanation:

  • def greet(name = "world"): The parameter name has a default value of "world".
  • greet: The method is called without arguments, so the default value is used.
  • greet("Alice"): The method is called with the argument "Alice", which overrides the default value.

  1. Variable Number of Arguments

Ruby allows you to define methods that can accept a variable number of arguments using the splat operator (*).

def sum(*numbers)
  numbers.reduce(0) { |total, num| total + num }
end

puts sum(1, 2, 3, 4)
# Output: 10

Explanation:

  • def sum(*numbers): The splat operator allows the method to accept any number of arguments, which are collected into an array named numbers.
  • numbers.reduce(0) { |total, num| total + num }: The reduce method is used to sum all the elements in the numbers array.

  1. Method Overloading

Ruby does not support method overloading in the traditional sense (i.e., defining multiple methods with the same name but different parameters). However, you can achieve similar functionality using default parameters and variable arguments.

def display_info(name, age = nil)
  if age
    puts "Name: #{name}, Age: #{age}"
  else
    puts "Name: #{name}"
  end
end

display_info("Alice")
# Output: Name: Alice

display_info("Bob", 30)
# Output: Name: Bob, Age: 30

Explanation:

  • def display_info(name, age = nil): The method display_info takes one required parameter (name) and one optional parameter (age).
  • The method body checks if age is provided and prints the appropriate message.

  1. Scope and Visibility

Methods defined within a class are instance methods by default and can be called on instances of the class. Methods can also be private or protected, affecting their visibility.

class Person
  def initialize(name)
    @name = name
  end

  def greet
    puts "Hello, #{@name}!"
  end

  private

  def secret
    puts "This is a secret method."
  end
end

person = Person.new("Alice")
person.greet
# Output: Hello, Alice!

# person.secret
# This will raise an error because `secret` is a private method.

Explanation:

  • class Person: Defines a class named Person.
  • def initialize(name): The constructor method initializes an instance variable @name.
  • def greet: An instance method that prints a greeting.
  • private: The secret method is private and cannot be called from outside the class.

Practical Exercises

Exercise 1: Simple Calculator

Create a method calculate that takes three parameters: two numbers and an operator (+, -, *, /). The method should perform the specified operation and return the result.

def calculate(num1, num2, operator)
  case operator
  when "+"
    num1 + num2
  when "-"
    num1 - num2
  when "*"
    num1 * num2
  when "/"
    num1 / num2
  else
    "Invalid operator"
  end
end

puts calculate(10, 5, "+")
# Output: 15

puts calculate(10, 5, "-")
# Output: 5

puts calculate(10, 5, "*")
# Output: 50

puts calculate(10, 5, "/")
# Output: 2

Exercise 2: Greeting with Time of Day

Create a method greet_with_time that takes a name and an optional time of day (morning, afternoon, evening). The method should print a greeting that includes the time of day.

def greet_with_time(name, time_of_day = "day")
  puts "Good #{time_of_day}, #{name}!"
end

greet_with_time("Alice")
# Output: Good day, Alice!

greet_with_time("Bob", "morning")
# Output: Good morning, Bob!

Summary

In this section, you learned about methods in Ruby, including how to define and call them, use parameters, return values, and handle variable numbers of arguments. You also explored method overloading and visibility. Methods are a fundamental part of Ruby programming, enabling you to write reusable and organized code. In the next module, we will delve into working with collections in Ruby.

© Copyright 2024. All rights reserved