我不确定这是什么,但让我来告诉你问题所在.
def factors num
(1..num).select {|n| num % n == 0}
end
def mutual_factors(*nums)
nums
.map { |n| factors(n) }
.inject(:&)
end
p mutual_factors(50, 30) # [1, 2, 5, 10]
p mutual_factors(50, 30, 45, 105) # [1, 5]
p mutual_factors(8, 4) # [1, 2, 4]
p mutual_factors(8, 4, 10) # [1, 2]
p mutual_factors(12, 24) # [1, 2, 3, 4, 6, 12]
p mutual_factors(12, 24, 64) # [1, 2, 4]
p mutual_factors(22, 44) # [1, 2, 11, 22]
p mutual_factors(22, 44, 11) # [1, 11]
p mutual_factors(7) # [1, 7]
p mutual_factors(7, 9) # [1]
with this being the portion in questioning:
nums
.map { |n| factors(n) }
.inject(:&)
好的,这是我的思维轨迹:首先,map
使用helper方法获取因子,并将因子输出到另一个数组中,然后该数组被注入?
我认为
.inject(:&)
是什么让我讨厌.我在上面运行了一个快速的谷歌,但除了数组求和和之类的基本功能,我还没有使用inject.我也做过类似的事情
test = "hello".split("").map(&:upcase)
p test.join
但是.inject(:&)
?我知道&;是一个过程,但我只在争论中使用过.我不知道幕后的基本原理.请在向我解释这一点时考虑我的当前级别=),我知道基本注入是如何工作的,还有splat操作符.