gpt4 book ai didi

带链接的 Ruby 枚举器

转载 作者:太空宇宙 更新时间:2023-11-03 17:48:51 26 4
gpt4 key购买 nike

我是Ruby新手,对下面的代码不是很懂。

n = [1,2,3]
n.map!.select{|x| x+=1}
puts n.inspect

会给我

[nil, nil, nil]

我知道 n.map!会给我一个枚举器,但我不明白为什么调用 select 会使 n 变为 nil。我知道那张 map !将修改原始对象,我只是不明白这是如何实现的。

更新:

我试过 n.map!.select {|x| true},n 仍然是 [nil, nil, nil]

非常感谢您的帮助!谢谢!

最佳答案

因为使用了select方法进行选择。它返回满足您放置在 block 中的条件的元素。在你的例子中,你没有设置任何条件,所以它返回了 nil

例如你想做这样的事情:

n = [1,2,3]
n.select { |num| num < 3 }

#=> This should return
#=> [1,2]

关于带链接的 Ruby 枚举器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28665152/

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