gpt4 book ai didi

Ruby 注入(inject)菊花链?

转载 作者:行者123 更新时间:2023-12-05 01:52:54 28 4
gpt4 key购买 nike

我不确定这是什么糖语法,但让我向您展示问题所在。

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]

这是提问的部分:

nums
.map { |n| factors(n) }
.inject(:&)

好吧,我的心理轨迹是这样的:首先,map使用辅助方法获取因子,并将因子输出到另一个数组中,然后注入(inject)那个数组?

我觉得

.inject(:&)

是什么让我失望。我对它进行了快速谷歌搜索,但除了求和数组和类似的基本内容之外,我没有将注入(inject)用于很多其他事情。我也做过类似的事情

test =  "hello".split("").map(&:upcase)
p test.join

但是 .inject(:&) 呢?我知道 & 是一个过程,但我只在参数中使用过它们。我不知道引擎盖下的基本原理。请在尝试向我解释时考虑我当前的水平 =),我知道基本注入(inject)的工作原理,也知道 splat 运算符。

最佳答案

部分引用来自 Enumerable#inject 的文档.

inject(symbol) → object

[...]

Returns an object formed from operands via either:

A method named by symbol.

[...]

With method-name argument symbol, combines operands using the method:

# Sum, without initial_operand.
(1..4).inject(:+) # => 10

这意味着在 inject 的上下文中,(:&) 不是一个过程,而只是告诉 inject 什么的符号 :&执行合并数组中元素的操作。

让我们看这个例子:

mutual_factors(8, 4, 10)
#=> [1, 2]

让我们看看每一步发生了什么:

nums
.map { |n| factors(n) } #=> [[1, 2, 4, 8], [1, 2, 4], [1, 2, 5, 10]]
.inject(:&) #=> [1, 2, 4, 8] & [1, 2, 4] & [1, 2, 5, 10]

Array#&是一种返回新数组的方法,该数组包含在两个数组中找到的每个元素(省略重复项)。

关于Ruby 注入(inject)菊花链?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71368847/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com