gpt4 book ai didi

ruby - :& argument mean? 是什么意思

转载 作者:行者123 更新时间:2023-12-02 01:45:03 24 4
gpt4 key购买 nike

我不明白此示例中注入(inject)方法的 :& 参数:

[1, 2].map do |id|
my_custom_method(MyModel.find(id))
end).inject(:&).map(&:category).uniq.compact.sort

:+ 对我来说很有意义:

[1, 2, 3].inject(:+)

等同于:

[1, 2, 3].inject { |sum, number| sum + number }

如上例所示,:& 是什么意思?

最佳答案

Enumerable#inject

If you specify a symbol instead, then each element in the collection will be passed to the named method of memo

所以&就是Integer#&方法

Bitwise AND; each bit in the result is 1 if both corresponding bits in self and other are 1, 0 otherwise

[7, 5].inject(:&) # => 5

与此相同

7 & 5 # => 5

它是如何工作的

7.to_s(2) # => "111"
5.to_s(2) # => "101"
7: 1 1 1
& & &
5: 1 0 1
--------
5: 1 0 1

关于ruby - :& argument mean? 是什么意思,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71012274/

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