Search code examples
rubycoding-stylerefactoringreadability

How to refactor this Ruby code?


I created the following, that works, but it seems very cryptic. Is there a way to write it in a more Ruby-esque or understandable way?

This method removes the lower factors below a number. So, 10.high_factors returns [6,7,8,9,10]. 6 is divisible by 2, so 2 is removed. There are no multiples greater than 6 on the list, so it stays.

class Fixnum
  def high_factors
    # Get the numbers that are not divisible by lower ones below self
    list = (2..self).to_a
    2.upto(self).each do |i|
      ((i+1)..self).each { |j| list.delete i if j.is_divisible_by? i }
    end

    list
  end

  def is_divisible_by? divisor
    self % divisor == 0
  end
end

Ruby 1.9.3


Solution

  • The result of your method will always be a list of the numbers from (N/2) + 1 to N.

    For every i<=(N/2), 2*i will also be on the list.

    For every j >= (N/2)+1 on the list, there will not be a k=x*j on it where x is an integer greater than 1, because 2*j > N.

    Therefore, if your method returns just ((self/2 + 1)..self).to_a it will also work as you wish.