Search⌘ K
AI Features

Introduction to Methods in Ruby

Explore how to define and use methods in Ruby to enhance code readability and maintainability. Understand the concept of code refactoring by creating reusable functions for common tasks such as calculating the highest common factor. This lesson helps you build foundational skills in writing clean and efficient Ruby programs.

Code refactoring

When constructing a solution for finding the HCF of two numbers, we need first to find the divisors of both numbers. In the following code, which gets the divisors for two input numbers, we can see the two code fragments that are almost identical.

Identical codes

Ruby
# finding divisor list for num1
puts "Enter first number: "
num1 = gets.chomp.to_i
(1..num1).each do |x|
check = num1 % x
if check == 0
divisors_list_1 << x
end
end
# finding divisor list for num1
puts "Enter second number: "
num2 = gets.chomp.to_i
(1..num2).each do |x|
check = num2 % x
divisors_list_2 << x if check == 0
end

The code on lines 2–9 is identical to the code on lines 12–17. This is not optimal, and we can create a method to improve the code quality.

Code refactoring is the process of restructuring existing code—without changing its external behavior. To put it in simple words: works the same on the outside, improved on the inside.

In programming, methods (also known as functions) remove duplication to make the code more readable and, most importantly, easier to maintain.

Method

...