我在学习 Ruby 的同时解决了一些关于 codewars 的问题。我解决了这个一个更C ++ -杂交的方式(我还是新来的Ruby)
然后我来检查基于upvotes的最佳解决方案,即:
def unique_in_order(iterable)
(iterable.is_a?(String) ? iterable.chars : iterable).chunk { |x| x }.map(&:first)
end
Run Code Online (Sandbox Code Playgroud)
我不知道那(&:first)是什么。我知道地图的作用,并且在我运行时看起来:
[1, 2, 3, 4, 4, 5].chunk {|x| x}.map(&:first)
Run Code Online (Sandbox Code Playgroud)
删除重复的元素。
根据docs,chunk枚举项目,根据块的返回值将它们组合在一起:
[1, 2, 3, 4, 4, 5].chunk {|x| x}.to_a
=> [[1, [1]],
[2, [2]],
[3, [3]],
[4, [4, 4]],
[5, [5]]]
Run Code Online (Sandbox Code Playgroud)
然后你只选择每个子数组的第一个元素:
[1, 2, 3, 4, 4, 5].chunk {|x| x}.map(&:first)
=> [1, 2, 3, 4, 5]
Run Code Online (Sandbox Code Playgroud)
map(&:first) 只是一个捷径 map {|e| e.first}