【发布时间】:2012-09-10 02:34:24
【问题描述】:
我创建了以下内容,但它看起来很神秘。有没有办法以更 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
Ruby 1.9.3
【问题讨论】:
-
我不明白这个...为什么不直接返回 [self/2+1 .. self]
标签: ruby coding-style refactoring readability