Getting the least common multiple of an array of integers in Ruby

In addition to tokland's answer, if you really want an #lcm method to act on an array of integers, you could add an instance method to the Array class.

class Array
  def lcm
    self.reduce(1, :lcm)
  end
end

puts 10.lcm(15)
# => 30
puts [5,3,10,2,20].lcm
# => 60

(This practice is called Monkey patching, as you're extending a class at runtime. Some people do frown upon the practice though.)


Any operation that takes two operands can be applied iteratively to a collection by folding it: Enumerable#inject/reduce. To cover the empty case, pass as first argument the identity element of the operation, which is 1 for the least common denominator.

[5, 3, 10, 2, 20].reduce(1) { |acc, n| acc.lcm(n) } # => 60

Which can be also written as:

[5, 3, 10, 2, 20].reduce(1, :lcm)

Tags:

Ruby