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
- Defining a Method
- Calling a Method
- Method Parameters
- Return Values
- Default Parameters
- Variable Number of Arguments
- Method Overloading
- Scope and Visibility
- 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.
Explanation:
def greet
: This line starts the method definition with the namegreet
.puts "Hello, world!"
: This is the body of the method, which prints "Hello, world!" to the console.end
: This line ends the method definition.
- 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.
- Method Parameters
Methods can accept parameters, which are specified within parentheses after the method name. These parameters act as local variables within the method.
Explanation:
def greet(name)
: The methodgreet
now takes one parameter,name
.puts "Hello, #{name}!"
: The method prints a greeting that includes the value ofname
.
- 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.
Explanation:
def add(a, b)
: The methodadd
takes two parameters,a
andb
.return a + b
: The method returns the sum ofa
andb
.result = add(2, 3)
: The method is called with arguments2
and3
, and the result is stored in the variableresult
.
- 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 parametername
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.
- 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 namednumbers
.numbers.reduce(0) { |total, num| total + num }
: Thereduce
method is used to sum all the elements in thenumbers
array.
- 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 methoddisplay_info
takes one required parameter (name
) and one optional parameter (age
).- The method body checks if
age
is provided and prints the appropriate message.
- 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 namedPerson
.def initialize(name)
: The constructor method initializes an instance variable@name
.def greet
: An instance method that prints a greeting.private
: Thesecret
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.
Ruby Programming Course
Module 1: Introduction to Ruby
Module 2: Basic Ruby Concepts
Module 3: Working with Collections
Module 4: Object-Oriented Programming in Ruby
- Classes and Objects
- Instance Variables and Methods
- Class Variables and Methods
- Inheritance
- Modules and Mixins
Module 5: Advanced Ruby Concepts
Module 6: Ruby on Rails Introduction
- What is Ruby on Rails?
- Setting Up Rails Environment
- Creating a Simple Rails Application
- MVC Architecture
- Routing
Module 7: Testing in Ruby
- Introduction to Testing
- Unit Testing with Minitest
- Behavior-Driven Development with RSpec
- Mocking and Stubbing