Solution: Finding the HCF by Using a Method
Take a look at the solution to the problem from the previous lesson and see the method call in action.
We'll cover the following...
Solution
def get_divisors(num) array = [] (1..num).each do |x| check = num % x if check == 0 array << x end end return array end puts "Enter first number: " num1 = gets.chomp.to_i divisors_list_1 = get_divisors(num1) puts "Enter second number: " num2 = gets.chomp.to_i divisors_list_2 = get_divisors(num2) d1sorted = divisors_list_1.sort.reverse d1sorted.each do |elem| if divisors_list_2.include?(elem) puts "The HCF is #{elem}" break end end
Finding the HCF using method
Explanation
Lines 1–10: Defines a method named
get_divisors
, which accepts a numbernum
and returns an array containing a list of ...