如何重构这个Ruby代码?
我创建了以下内容,这是可行的,但它似乎非常神秘。有没有一种方法可以用一种更像Ruby或者更容易理解的方式来写呢 此方法删除数字以下的较低因子。因此,10.高_因子的回报率[6,7,8,9,10]。6可以被2整除,所以2被移除。列表中没有大于6的倍数,因此它保持不变如何重构这个Ruby代码?,ruby,coding-style,refactoring,readability,Ruby,Coding Style,Refactoring,Readability,我创建了以下内容,这是可行的,但它似乎非常神秘。有没有一种方法可以用一种更像Ruby或者更容易理解的方式来写呢 此方法删除数字以下的较低因子。因此,10.高_因子的回报率[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..
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这个怎么样?只是去掉那些可以被上面的数字整除的数字
class Fixnum
def high_factors
# Get the numbers that are not divisible by lower ones below self
(2..self).reject do |i|
(i+1..self).any? { |j| j.divisible_by?(i) }
end
end
def divisible_by?(divisor)
self % divisor == 0
end
end
ps:在ruby中,在布尔函数的开头省略“is”是很常见的,因为我们可以添加?方法的结果将始终是从N/2+1到N的数字列表 对于列表中的每一个i=N/2+1,其中x是大于1的整数,因为2*j>N,所以不会有k=x*j 因此,如果您的方法只返回self/2+1..self.to_a,它也将按照您的意愿工作。这是我的方法
def high_factors
ary = (2..self).to_a
ary.reject do |factor|
ary.index {|num| num != factor and num % factor == 0}
end
end
它可以工作,因为如果无法找到合适的匹配项,Arrayindex将返回nil 我不明白这个。。。为什么不直接返回[self/2+1..self]尽管这没有重构任何Ruby代码,但它确实是最好的答案,因为它使用数学来证明正确性。