Introduction to Methods in Ruby
Learn about methods in Ruby and their significance.
We'll cover the following...
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
# finding divisor list for num1puts "Enter first number: "num1 = gets.chomp.to_i(1..num1).each do |x|check = num1 % xif check == 0divisors_list_1 << xendend# finding divisor list for num1puts "Enter second number: "num2 = gets.chomp.to_i(1..num2).each do |x|check = num2 % xdivisors_list_2 << x if check == 0end
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.