DEV Community

Cover image for Mastering Ruby Methods: 16 Practical Examples for Beginners
gerry leo nugroho
gerry leo nugroho

Posted on

Mastering Ruby Methods: 16 Practical Examples for Beginners

Methods are one of the fundamental building blocks of Ruby programming. They allow us to write reusable, modular code, making our programs more efficient and readable. In this guide, we will explore 16 essential Ruby methods with detailed explanations, example outputs, and links to official documentation site. By the end of this post, you will have a solid grasp of how methods work in Ruby and how to use them effectively in your projects. Here's where you can play around without installing or updating your current Ruby interpreter in your system.


1. Defining and Calling a Simple Method in Ruby

A method in Ruby is defined using the def keyword, followed by the method name and a block of code. The method only executes when explicitly called.

def greet
  puts "Hello, welcome to the world of Ruby!"
end

greet
Enter fullscreen mode Exit fullscreen mode

Output:

Hello, welcome to the world of Ruby!
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • The greet method is defined.
  • When greet is called, it prints a message to the console.

πŸ”— Official Ruby Documentation - Methods


2. Ruby Method with Parameters

Methods in Ruby can accept parameters, allowing them to operate on different values.

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

puts add(5, 10)
Enter fullscreen mode Exit fullscreen mode

Output:

15
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • The add method takes two parameters: a and b.
  • It returns the sum of a and b.
  • We call add(5, 10), which returns 15.

πŸ”— Understanding Ruby Parameters


3. Returning an Array from a Method

A Ruby method can return an array, allowing multiple values to be returned.

def favorite_fruits
  return ["Apple", "Banana", "Grapes"]
end

puts favorite_fruits.inspect
Enter fullscreen mode Exit fullscreen mode

Output:

["Apple", "Banana", "Grapes"]
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • The method favorite_fruits returns an array of fruit names.
  • .inspect is used to print the array in a readable format.

πŸ”— Understanding Array in Ruby


4. Returning a Hash from a Method

def person_info
  return { name: "John Doe", age: 30, city: "New York" }
end

puts person_info.inspect
Enter fullscreen mode Exit fullscreen mode

Output:

{:name=>"John Doe", :age=>30, :city=>"New York"}
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • The method person_info returns a hash with three key-value pairs.

πŸ”— Learn More About Ruby Hashes


5. Default Parameter Values in Ruby Methods

You can specify default values for method parameters.

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

greet

greet("Alice")
Enter fullscreen mode Exit fullscreen mode

Output:

Hello, Guest!
Hello, Alice!
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • The name parameter defaults to "Guest" if no argument is passed.
  • When greet("Alice") is called, "Alice" replaces the default value.

πŸ”— Parameter Values in Ruby Methods


6. Methods with Variable Number of Arguments

Ruby allows passing an arbitrary number of arguments using the splat (*) operator.

def sum(*numbers)
  numbers.sum
end

puts sum(1, 2, 3, 4, 5)
Enter fullscreen mode Exit fullscreen mode

Output:

15
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • *numbers collects all arguments into an array.
  • sum calculates the total of all elements.

πŸ”— Working with Variable Arguments


7. Ruby Method to Check for Palindrome

def palindrome?(string)
  string == string.reverse
end

puts palindrome?("racecar")
puts palindrome?("hello")
Enter fullscreen mode Exit fullscreen mode

Output:

true
false
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • The method compares a string with its reversed version.
  • If both are equal, the word is a palindrome.

πŸ”— Ruby Method to Check for Palindrome


8. Factorial Calculation in Ruby

def factorial(n)
  (1..n).inject(:*) || 1
end

puts factorial(5)
Enter fullscreen mode Exit fullscreen mode

Output:

120
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • (1..n).inject(:*) multiplies all numbers from 1 to n.
  • The || 1 ensures that factorial(0) returns 1.

πŸ”— Factorial with Ruby


9. Swapping Two Numbers Using a Ruby Method

def swap(a, b)
  a, b = b, a
  return a, b
end

x, y = swap(10, 20)
puts "Swapped values: #{x}, #{y}"
Enter fullscreen mode Exit fullscreen mode

Output:

Swapped values: 20, 10
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • Parallel assignment swaps values without needing a temporary variable.

πŸ”— Swapping Two Numbers Using a Ruby Method


10. Nested Methods in Ruby

Ruby doesn’t support defining methods inside methods, but we can use blocks or lambdas for similar behavior.

def outer_method
  inner_method = -> { puts "I am inside a nested method!" }
  inner_method.call
end

outer_method
Enter fullscreen mode Exit fullscreen mode

Output:

I am inside a nested method!
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • The lambda inner_method acts like a nested function.

πŸ”— Lambda Functions in Ruby


11. Passing an Array as an Argument

Sometimes, you might need to process an entire array inside a method.

def print_languages(languages)
  languages.each { |lang| puts lang }
end

langs = ["Ruby", "Python", "JavaScript"]
print_languages(langs)
Enter fullscreen mode Exit fullscreen mode

Output:

Ruby
Python
JavaScript
Enter fullscreen mode Exit fullscreen mode

Explanation

  • The method accepts an array as an argument.
  • each iterates over the array, printing each language.

πŸ”— Ruby Docs on Arrays


12. Passing a Hash as an Argument

def print_student_details(student)
  student.each { |key, value| puts "#{key.capitalize}: #{value}" }
end

student_info = { name: "Alice", age: 21, major: "Computer Science" }
print_student_details(student_info)
Enter fullscreen mode Exit fullscreen mode

Output:

Name: Alice
Age: 21
Major: Computer Science
Enter fullscreen mode Exit fullscreen mode

Explanation

  • This method takes a hash and iterates through it using each.
  • We capitalize the keys (name, age, etc.) for better formatting.

πŸ”— Ruby Docs on Hashes


13. Using the Splat Operator (*) for Variable Arguments

Ruby allows passing any number of arguments using the * operator.

def list_numbers(*nums)
  puts "Numbers: #{nums.join(', ')}"
end

list_numbers(1, 2, 3, 4, 5)
list_numbers(10, 20)
Enter fullscreen mode Exit fullscreen mode

Output:

Numbers: 1, 2, 3, 4, 5
Numbers: 10, 20
Enter fullscreen mode Exit fullscreen mode

Explanation

  • The *nums captures multiple arguments into an array.
  • We use .join(', ') to format the output nicely.

πŸ”— Ruby Docs on Splat Operator


14. Using Blocks with Methods

Blocks in Ruby allow passing chunks of code to a method.

def greet_user(name)
  puts "Hello, #{name}!"
  yield if block_given?
end

greet_user("John") { puts "Welcome to Ruby programming!" }
Enter fullscreen mode Exit fullscreen mode

Output:

Hello, John!
Welcome to Ruby programming!
Enter fullscreen mode Exit fullscreen mode

Explanation

  • The yield keyword executes the block passed to the method.
  • The condition if block_given? ensures that yield is only called if a block is provided.

πŸ”— Ruby Docs on Blocks


15. Method That Uses a Proc

A Proc is an object that encapsulates a block of code.

def execute_proc(my_proc)
  puts "Before executing proc"
  my_proc.call
  puts "After executing proc"
end

greeting_proc = Proc.new { puts "This is a Ruby Proc!" }
execute_proc(greeting_proc)
Enter fullscreen mode Exit fullscreen mode

Output:

Before executing proc
This is a Ruby Proc!
After executing proc
Enter fullscreen mode Exit fullscreen mode

Explanation

  • We create a Proc using Proc.new.
  • The method calls my_proc.call to execute the stored block of code.

πŸ”— Ruby Docs on Procs


16. Using a Lambda Function

Lambdas are similar to Procs but behave more like methods.

def execute_lambda(my_lambda)
  puts "Before executing lambda"
  my_lambda.call
  puts "After executing lambda"
end

greeting_lambda = -> { puts "Hello from a Lambda!" }
execute_lambda(greeting_lambda)
Enter fullscreen mode Exit fullscreen mode

Output:

Before executing lambda
Hello from a Lambda!
After executing lambda
Enter fullscreen mode Exit fullscreen mode

Explanation

  • A lambda is created using -> { ... }.
  • It is more strict than a Proc in how it handles arguments.
  • The method calls my_lambda.call to execute the function.

πŸ”— Ruby Docs on Lambdas


Understanding methods in Ruby is essential for writing clean and maintainable code. By practicing these examples, you will gain confidence in defining and using methods effectively. Experiment with these concepts in your own projects to deepen your understanding.

πŸ”₯ Key Takeaways

  • Methods help avoid code repetition and improve readability.
  • Methods can accept parameters, arrays, hashes, and keyword arguments.
  • Ruby supports default values, blocks, Procs, and Lambdas.
  • Understanding these concepts is essential for mastering Ruby development.

πŸš€ Happy coding!

Top comments (0)