[英]How to refactor this Ruby code?
我創建了以下內容,該方法可以正常工作,但似乎很神秘。 有沒有辦法以更像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
方法的結果將始終是(N/2) + 1
至N
的數字列表。
對於每個i<=(N/2)
, 2*i
也將出現在列表中。
對於列表中的每個j >= (N/2)+1
,由於2*j > N
,因此k=x*j
上的k=x*j
不會是k=x*j
1的整數。
因此,如果您的方法僅返回((self/2 + 1)..self).to_a
則它也將按您希望的那樣工作。
那這個呢? 只需刪除可被高整數整除的數字。
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_”,因為我們可以添加?。
這是我的
def high_factors
ary = (2..self).to_a
ary.reject do |factor|
ary.index {|num| num != factor and num % factor == 0}
end
end
它起作用,因為如果找不到合適的匹配項,則Array#index返回nil。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.