这个Ruby代码中的chunk和map组合有什么作用?

3
我正在学习Ruby,同时在Codewars上解决一些问题。我用更像是C++的方式解决了这个问题(我对Ruby还很陌生)。
然后我来查看基于投票数的最佳解决方案,它是:
def unique_in_order(iterable)
  (iterable.is_a?(String) ? iterable.chars : iterable).chunk { |x| x }.map(&:first)
end

我不知道(&:first)是什么意思。我知道map的作用,当我运行时似乎:
[1, 2, 3, 4, 4, 5].chunk {|x| x}.map(&:first)

重复的元素被移除。

1
如果问题只是关于&:first bit,请参见https://dev59.com/vHM_5IYBdhLWcg3wzmrL。请返回翻译后的文本。 - Frederick Cheung
1个回答

5
根据文档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} 的快捷方式。


3
[1, 2, 3, 4, 4, 5]。.chunk(&:itself).map(&:first) - steenslag
@steenslag 很棒!Ruby真是太美了。 - fatg
用通俗易懂的语言来说,这个方法可以去除重复项,但只有当它们是连续的时才能去除。 - Eric Duminil

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接