为什么uniq在Ruby中的map之后返回数组的原始值?

时间:2019-03-19 14:34:34

标签: ruby

我尝试了以下代码:

<div id="selector" onclick="getKids(this, 'selector-2', 2);" 
    style="padding:5px;width:10px;background-color:red;"
>
    <div id="selector-1"></div>
    <div id="selector-2"></div>
    <div id="selector-3"></div>
</div>

我的理解是numbers = [1,2,2,3,4] numbers.map.uniq {|number| number < 2 } 的返回值传递给map。我预期:

uniq

相反,我收到了:

[true, false]

似乎[1, 2] 维护着对原始数组的引用。

有人可以提供这种行为的见解吗?

3 个答案:

答案 0 :(得分:5)

Array#uniq accepts a block, defining the condition on what should be treated 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]

The latter returns one odd and one non-odd (even) element. In your case it returns 1 element that is less than 2 and one element that is greater or equal to two.


Note, that map enumerator is effectively there:

numbers.each &Math.method(:sqrt)
#⇒ [1.0, 1.4142135623730951, 1.4142135623730951,
#        1.7320508075688772, 2.0]

答案 1 :(得分:3)

您实际上并没有对map调用做任何事情,您的功能大致等同于此:

[1,2,2,3,4].uniq {|number| p number < 2 }

类似map的方法返回Enumerable类型,然后您在该uniq上调用Enumerable。来自Ruby docs

  

如果没有给出块,则返回一个枚举器。

实际上,您的地图是禁止操作的。

我认为您也误解了uniq方法。 Uniq将从一个数组中过滤出所有不唯一的元素(例如:[1, 1, 2, 3, 3, 4, 5].uniq == [1, 2, 3, 4, 5]),而不返回该元素在数组中是唯一的(真还是假)。

答案 2 :(得分:-1)

numbers.uniq.map { |number| number < 2 }


uniq method

uniq → new_ary click to toggle source uniq {|item| ...} → new_ary Returns a new array by removing duplicate values in self.

If a block is given, it will use the return value of the block for comparison. It compares values using their hash and eql? methods for efficiency. self is traversed in order, and the first occurrence is kept.

a = [ "a", "a", "b", "b", "c" ]

a.uniq # => ["a", "b", "c"]

b = [["student","sam"], ["student","george"], ["teacher","matz"]]

b.uniq {|s| s.first} # => [["student", "sam"], ["teacher", "matz"]]

You can read more about uniq method here.