块和映射的这种组合在Ruby中起什么作用?

块和映射的这种组合在Ruby中起什么作用?,ruby,Ruby,在学习Ruby时,我正在解决一些关于代码战的问题。我用一种更像C++的方式解决了这个问题(我还是Ruby新手) 然后我来检查基于UPVOUTS的最佳解决方案,即: def unique_in_order(iterable) (iterable.is_a?(String) ? iterable.chars : iterable).chunk { |x| x }.map(&:first) end 我不知道(&:first)是什么。我知道地图的作用,当我跑步时,它看起来: [1, 2,

在学习Ruby时,我正在解决一些关于代码战的问题。我用一种更像C++的方式解决了这个问题(我还是Ruby新手)

然后我来检查基于UPVOUTS的最佳解决方案,即:

def unique_in_order(iterable)
  (iterable.is_a?(String) ? iterable.chars : iterable).chunk { |x| x }.map(&:first)
end
我不知道
(&:first)
是什么。我知道地图的作用,当我跑步时,它看起来:

[1, 2, 3, 4, 4, 5].chunk {|x| x}.map(&:first)
重复的元素将被删除。

根据,
chunk
枚举项,并根据块的返回值将它们分块:

[1, 2, 3, 4, 4, 5].chunk {|x| x}.to_a
=> [[1, [1]],
    [2, [2]],
    [3, [3]], 
    [4, [4, 4]],
    [5, [5]]]
然后仅选择每个子阵列的第一个元素:

[1, 2, 3, 4, 4, 5].chunk {|x| x}.map(&:first)
=> [1, 2, 3, 4, 5]

map(&:first)
只是
map{e | e.first}

如果问题只是关于&:first位,请参见或
[1,2,3,4,4,5]。chunk(&:本身)。map(&:first)
@steenslag-night!Ruby在通俗易懂的英语中非常漂亮:这种方法可以删除重复项,但前提是它们是连续的。