A method in Ruby is a reusable block of code that performs a specific task and optionally returns a value. Methods help reduce repetition by letting you define logic once and call it multiple times.
In Ruby, methods are defined using the def keyword and closed with end. Method names are typically written in lowercase (snake_case).
Defining and Calling a Method
A method must be defined before it can be called.
Basic Syntax
def method_name
# statements
end
Example:
def welcome
puts "Hello! Welcome to Ruby Programming."
end
welcome
Output:
Hello! Welcome to Ruby Programming.
Passing Parameters to Methods
You can pass values into a method using parameters. Ruby also supports default parameter values, which are used if the caller does not provide an argument.
Example with Default Values
def display_info(name = "Ruby", level = "Beginner")
puts "Language: #{name}"
puts "Level: #{level}"
end
display_info "Python", "Intermediate"
puts ""
display_info
Output:
Language: Python
Level: Intermediate
Language: Ruby
Level: Beginner
Accepting a Variable Number of Arguments
When the number of arguments is unknown, Ruby lets you collect them using the splat operator *.
Example-
def show_items(*items)
puts "Number of items: #{items.length}"
items.each_with_index do |item, index|
puts "Item #{index + 1}: #{item}"
end
end
show_items "Apple", "Banana", "Cherry"
show_items "Orange"
Returning Values from Methods
Ruby automatically returns the value of the last evaluated expression. You only need return when you want to exit early or return multiple values explicitly.
Eg:
def calculate_sum
num1 = 25
num2 = 75
num1 + num2
end
puts "The sum is: #{calculate_sum}"
Method Visibility in Ruby
Method visibility determines where methods can be called from. Ruby provides three access levels:
- public (default): callable from anywhere
- protected: callable within the class and its subclasses, often for comparisons between instances
- private: callable only inside the class, and not with an explicit receiver (even
self)
Public Methods Example
class Example
def public_method1
puts "public_method1 called!"
end
public
def public_method2
puts "public_method2 called!"
end
end
obj = Example.new
obj.public_method1
obj.public_method2
Protected Methods Example
class Parent
protected
def protected_method
puts "protected_method called!"
end
end
class Child < Parent
def call_protected
protected_method
end
end
Child.new.call_protected
Private Methods Example
class Example
private
def private_method
puts "private_method called!"
end
public
def public_method
private_method
end
end
Example.new.public_method
Recursion in Ruby
Recursion happens when a method calls itself to solve a problem in smaller steps. It can make certain solutions elegant, but Ruby recursion can cause stack overflow for very large inputs.
Iterative vs Recursive Array Sum
Iterative:
def iterative_sum(numbers)
sum = 0
numbers.each { |n| sum += n }
sum
end
puts iterative_sum([1, 2, 3, 4, 5])
Recursive:
def recursive_sum(numbers)
return 0 if numbers.empty?
numbers[0] + recursive_sum(numbers[1..])
end
puts recursive_sum([1, 2, 3, 4, 5])
Recursive Factorial Example
def factorial(n)
return 1 if n <= 1
n * factorial(n - 1)
end
puts factorial(5)
Recursive Fibonacci Example
def fibonacci(n)
return n if n < 2
fibonacci(n - 1) + fibonacci(n - 2)
end
puts fibonacci(5)
Tip: recursive Fibonacci is slow for large values—use iteration or memoization in real projects.
Ruby Hook Methods
Hook methods are special methods triggered by events such as including a module, inheriting from a class, or calling undefined methods.
Common hook methods include:
includedprependedextendedinheritedmethod_missing
included Hook
module WelcomeMessage
def self.included(target)
puts "The #{target} has been greeted with a warm welcome!"
end
end
class User
include WelcomeMessage
end
prepended Hook
module Language
def self.prepended(target)
puts "#{self} has been prepended to #{target}"
end
def description
"The language used is Ruby."
end
end
class Programming
prepend Language
end
puts Programming.new.description
extended Hook
module Framework
def self.extended(target)
puts "#{self} was extended by #{target}"
end
def description
"This framework is based on Ruby."
end
end
class Software
extend Framework
end
puts Software.description
inherited Hook
class Vehicle
def self.inherited(subclass)
puts "#{subclass} is a subclass of Vehicle"
end
end
class Car < Vehicle
end
method_missing
class Language
def method_missing(method_name, *args)
"#{method_name} is not defined for #{self}"
end
def known_method
"This method is defined."
end
end
obj = Language.new
puts obj.known_method
puts obj.unknown_method
Ruby Range Class Methods and Examples
A Range represents a sequence between two values.
..includes the end value...excludes the end value
Creating Ranges
(1..6).to_a # => [1, 2, 3, 4, 5, 6]
(1...6).to_a # => [1, 2, 3, 4, 5]
Useful Range Methods
range = (3..10)
puts range.begin # 3
puts range.end # 10
puts range.first # 3
puts range.last # 10
puts range.include?(5) # true
puts range.include?(15) # false
Iteration with each and step
(1..5).each { |i| print "#{i} " }
puts ""
(1..10).step(2) { |i| print "#{i} " }
puts ""
Summary
Ruby methods make your code reusable and easier to maintain. In this guide, you learned how to:
- define and call methods
- pass parameters and defaults
- accept variable-length arguments
- return values naturally
- control method visibility (public/protected/private)
- use recursion safely
- use hook methods for metaprogramming
- work with Ruby ranges