3

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.

Ilya
  • 13,337
  • 5
  • 37
  • 53
fatg
  • 519
  • 7
  • 23

1 Answers1

5

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}

Ilya
  • 13,337
  • 5
  • 37
  • 53