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.
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
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.