ruby - Why does uniq return original value of array after map in Ruby?
问题描述
I tried the following code:
numbers = [1,2,2,3,4]
numbers.map.uniq {|number| number < 2 }
My understanding is that the return value of map
is passed to uniq
. I expected:
[true, false]
Instead, I received:
[1, 2]
It seems that uniq
maintains a reference to the original array.
Could someone provide insight into this behaviour?
解决方案
Array#uniq
接受一个块,定义应该处理的条件uniq
。
main > numbers = [1,2,2,3,4].map
#⇒ #<Enumerator: ...>
main > numbers.uniq
#⇒ [1, 2, 3, 4]
# effectively the same as
main > numbers.to_a.uniq
#⇒ [1, 2, 3, 4]
main > numbers.uniq { |number| number.odd? }
#⇒ [1, 2]
后者返回一个奇数和一个非奇数(偶数)元素。在您的情况下,它返回 1 个小于 2 的元素和一个大于或等于 2 的元素。
请注意,该map
枚举器有效地存在:
numbers.each &Math.method(:sqrt)
#⇒ [1.0, 1.4142135623730951, 1.4142135623730951,
# 1.7320508075688772, 2.0]
推荐阅读
- ssh - 是否可以仅使用 ppk 或 pem 文件通过 ssh 进入服务器?
- sql-server - 运行 Invoke-SqlCmd 时传递字符串参数?
- python - 如何在 Pandas 中将值从 1 列分配给另一列并发出警告
- html - 如何在弹性容器中设置间隙(排水沟)?
- reactjs - 无法使用 fontawesome pro 将 gatsby 站点部署到 Netlify
- javascript - babel-plugin-rewire: 测试私有方法
- oracle - 如何动态使用源/目标表进行合并以及在 Oracle 中动态选择更新语句的列
- c++ - 如何在 Ubuntu 的 VSCodium 中设置 Googletest
- string - Swift 5:识别字符串中所有不同的子字符串
- amazon-web-services - AWS RDS Aurora - 如何使用 PgAdmin 进行连接?