Skip to content

Ruby Methods

Ruby methods are blocks of code that perform a specific task. They are similar to functions in other programming languages and are used to bundle one or more repeatable statements into a single unit, promoting code reusability and organization.

Method names should conventionally begin with a lowercase letter or an underscore. If a method name starts with an uppercase letter, Ruby might interpret it as a constant, leading to parsing errors.

Methods must be defined before they are called; otherwise, Ruby will raise a NoMethodError exception.

def method_name(parameter1, parameter2, ...)
# expressions (method body)
# ...
end

A simple method without parameters:

#!/usr/bin/env ruby
def greet
puts "Hello, Ruby!"
end

A method with parameters:

#!/usr/bin/env ruby
def personalize_greeting(name)
puts "Hello, #{name}!"
end

You can set default values for parameters. These defaults are used if the method is called without providing arguments for those parameters.

#!/usr/bin/env ruby
def greet_with_default(name = "World")
puts "Hello, #{name}!"
end
greet_with_default # Output: Hello, World!
greet_with_default("Alice") # Output: Hello, Alice!

To call a method, simply use its name. If the method expects arguments, provide them.

#!/usr/bin/env ruby
def say_hello
puts "Hello!"
end
def add(a, b)
puts a + b
end
# Calling methods
say_hello # Call without parentheses if no arguments
add(5, 3) # Call with arguments
add 10, 20 # Parentheses are often optional if unambiguous

If a method requires a specific number of arguments, and you call it with a different number, Ruby will raise an ArgumentError.

#!/usr/bin/env ruby
def favorite_languages(lang1 = "Ruby", lang2 = "Python")
puts "My favorite programming language is #{lang1}."
puts "My second favorite is #{lang2}."
end
favorite_languages("JavaScript", "Go") # Uses provided arguments
puts "---"
favorite_languages("Rust") # lang1 is "Rust", lang2 uses default "Python"
puts "---"
favorite_languages # Uses both default values

This will produce:

My favorite programming language is JavaScript.
My second favorite is Go.
---
My favorite programming language is Rust.
My second favorite is Python.
---
My favorite programming language is Ruby.
My second favorite is Python.

Every method in Ruby implicitly returns the value of the last evaluated expression in its body.

#!/usr/bin/env ruby
def simple_calculator(a, b)
sum = a + b
difference = a - b
difference # This is the last evaluated expression, so it's returned
end
result = simple_calculator(10, 4)
puts "Result (difference): #{result}" # Output: Result (difference): 6

The return statement can be used to explicitly exit a method and return one or more values. If return is used without an expression, it returns nil. If multiple expressions are provided, return yields an array containing these values.

return
return expression
return expr1, expr2, expr3
#!/usr/bin/env ruby
def get_coordinates
x = 10
y = 20
z = 30
return x, y, z # Returns an array [10, 20, 30]
end
def get_status(code)
return "OK" if code == 200
return "Error" # Implicitly returns "Error" if code is not 200
end
coords = get_coordinates
puts "Coordinates: #{coords.inspect}" # Output: Coordinates: [10, 20, 30]
status_ok = get_status(200)
puts "Status for 200: #{status_ok}" # Output: Status for 200: OK
status_err = get_status(404)
puts "Status for 404: #{status_err}" # Output: Status for 404: Error

Variable Number of Parameters (Splat Operator)

Section titled “Variable Number of Parameters (Splat Operator)”

Ruby allows methods to accept a variable number of arguments using the splat operator (*). When used in a method definition, * collects any remaining arguments into an array.

#!/usr/bin/env ruby
def display_items(category, *items)
puts "Category: #{category}"
puts "Number of items: #{items.length}"
items.each_with_index do |item, index|
puts " Item #{index + 1}: #{item}"
end
end
display_items("Fruits", "Apple", "Banana", "Orange")
puts "---"
display_items("Colors", "Red", "Green")
puts "---"
display_items("Tools") # items will be an empty array

This produces:

Category: Fruits
Number of items: 3
Item 1: Apple
Item 2: Banana
Item 3: Orange
---
Category: Colors
Number of items: 2
Item 1: Red
Item 2: Green
---
Category: Tools
Number of items: 0

Ruby methods can also accept keyword arguments, which are specified by name when calling the method. This can make method calls more readable, especially when there are many parameters or boolean flags.

#!/usr/bin/env ruby
def create_user(name:, email:, admin: false, notify: true)
puts "Creating user: #{name}"
puts "Email: #{email}"
puts "Admin: #{admin}"
puts "Notify: #{notify}"
# ... logic to create user ...
end
create_user(name: "Alice", email: "alice@example.com")
puts "---"
create_user(name: "Bob", email: "bob@example.com", admin: true, notify: false)
# Using double splat (**) for arbitrary keyword arguments
def process_options(user_id, **options)
puts "Processing for user: #{user_id}"
options.each do |key, value|
puts " Option #{key}: #{value}"
end
end
process_options(101, theme: "dark", layout: "compact", show_help: true)

Class methods are methods defined on a class itself, rather than on instances of the class. They are often used for factory methods or utility functions related to the class.

You can define a class method by prefixing the method name with self. or the class name itself within the class definition.

#!/usr/bin/env ruby
class Utility
# Instance method
def instance_method
puts "This is an instance method."
end
# Class method using self.
def self.class_method_one
puts "This is class_method_one."
end
# Class method using the class name
def Utility.class_method_two
puts "This is class_method_two."
end
end
# Call class methods directly on the class
Utility.class_method_one
Utility.class_method_two
# To call an instance method, you need an instance
util_instance = Utility.new
util_instance.instance_method

By default, methods defined inside a class are public. Methods defined at the top level (outside any class or module) become private instance methods of the Object class.

The alias keyword creates an alias for an existing method or global variable. Aliases cannot be defined within a method body. When a method is aliased, the alias refers to the method’s definition at that point, even if the original method is later overridden.

alias_method is a method (typically used within classes/modules) that achieves the same for methods, often preferred for its flexibility (e.g., it can take symbols or strings as arguments).

alias new_method_name old_method_name
alias new_global_variable_name old_global_variable_name
# Within a class/module:
alias_method :new_method_name, :old_method_name
#!/usr/bin/env ruby
class Greeter
def welcome(name)
"Hello, #{name}!"
end
alias_method :greet, :welcome # Aliasing an instance method
end
my_greeter = Greeter.new
puts my_greeter.welcome("Original")
puts my_greeter.greet("Alias")
$global_var = "Initial Global"
alias $gvar $global_var # Aliasing a global variable
puts $gvar

Aliasing built-in numbered global variables like $1, $2 is prohibited. Overriding core global variables can lead to unexpected behavior.

The undef keyword cancels the definition of a method, making it no longer callable. It cannot appear inside a method body.

undef_method is its method-based counterpart, typically used within classes/modules.

undef method_name
# Within a class/module:
undef_method :method_name
#!/usr/bin/env ruby
class Calculator
def add(a, b)
a + b
end
def subtract(a, b)
a - b
end
end
calc = Calculator.new
puts calc.add(5, 3) # Output: 8
class Calculator
undef_method :add # Undefine the 'add' method
end
# calc.add(7, 2) # This would now raise a NoMethodError
puts calc.subtract(10, 4) # Output: 6

Using undef and alias can modify a class’s interface, potentially independently of its superclass. However, care must be taken as internal method calls within the class to self might break if methods are undefined.