gpt4 book ai didi

Ruby 试图掌握一种新的表示法。 (注入(inject)(: ) vs select(&:even?);为什么有&?)

转载 作者:数据小太阳 更新时间:2023-10-29 06:58:29 24 4
gpt4 key购买 nike

所以,我刚刚了解到,而不是写这样的东西:

[1,2,3,4,5].inject {|x,y| x + y} => 15

我会写

[1,2,3,4,5].inject(:+) => 15

我还了解到,而不是写作

[1,2,3,4,5].select {|x| x.even?} => [2,4]

我会写

[1,2,3,4,5].select(&:even?) => [2,4]

我的问题是为什么一个(选择)使用 & 而另一个(注入(inject))不使用。我确定 : 是因为 even?+ 被处理为符号,但我很想澄清为什么 & 用于一个以及为什么使用 :

此外,我知道我可以在 injectselect 之外做这些符号。

非常感谢!

最佳答案

& 运算符在这种情况下将符号转换为过程。所以代码在后台执行此操作:

[1,2,3,4,5].select {|elem| elem.send :even? } # => [2, 4]

inject 方法的实现认识到了对这些快捷方法规范的需求,并在符号作为参数传递时添加了特殊处理。因此,在这种情况下,它基本上执行 & 运算符的操作。

why one (select) uses the & and the other one (inject) doesn't

因为没有人以这种方式实现select。 Ruby 是开源的,他们甚至可以接受你的补丁。去解决这个问题:)

P.S.:但如果由我决定,我会删除注入(inject)的特殊处理。在 Symbol#to_proc(& 运算符使用的)的存在下感觉有点多余和困惑。

关于Ruby 试图掌握一种新的表示法。 (注入(inject)(: ) vs select(&:even?);为什么有&?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16605597/

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