...

/

Introduction to Methods in Ruby

Introduction to Methods in Ruby

Learn about methods in Ruby and their significance.

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

Press + to interact
# 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

...