首页 > 解决方案 > 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?

标签: ruby

解决方案


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]

推荐阅读