Gia Phat Ha Gia Phat Ha - 6 months ago 9
Ruby Question

What does this combination of chunk and map do in Ruby?

I'm solving some problems on codewars while learning Ruby. I solved this one in a more C++-ish way (I'm still new to Ruby)

Then I came to check the best solution based on upvotes, which is:

def unique_in_order(iterable)
(iterable.is_a?(String) ? iterable.chars : iterable).chunk { |x| x }.map(&:first)
end


I don't know what the (&:first) is. I know what map does and it seems when I run

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


the duplicate elements are removed.

Answer

According to docs, chunk enumerates over the items, chunking them together based on the return value of the block:

[1, 2, 3, 4, 4, 5].chunk {|x| x}.to_a
=> [[1, [1]],
    [2, [2]],
    [3, [3]], 
    [4, [4, 4]],
    [5, [5]]]

Then you choose only first element of each subarray:

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

map(&:first) is just a shortcut for map {|e| e.first}

Comments