B S*_*ven 0 ruby refactoring coding-style readability
我创建了以下内容,但是看起来非常神秘.有没有办法以更Ruby的方式或可理解的方式编写它?
此方法删除数字下方的较低因子.所以,10.high_factors回报[6,7,8,9,10].6可被2整除,因此2被删除.列表中没有大于6的倍数,因此它保持不变.
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
Run Code Online (Sandbox Code Playgroud)
Ruby 1.9.3
你的方法的结果总是从数字列表(N/2) + 1来N.
对于每一个i<=(N/2),2*i也将在列表中.
对于j >= (N/2)+1列表中的每一个,都不会有一个k=x*jx是大于1的整数,因为2*j > N.
因此,如果您的方法只返回((self/2 + 1)..self).to_a它也可以按您的意愿工作.