-3

I'm fairly new to ruby and I'm a bit confused by what the map! syntax does. I see the following line on the codebase

b.map(&:values).uniq!.map!

b.map(&:values).uniq! gives me the following output:

[["us"],
 ["au"],
 ["fr"],
 ["mx"],
 ["ad",
  "ae",
  "af",
  "al",
  "am",
  "ao",
  "aq"]]

When I add a .map! to the end of b.map(&:values).uniq! I get #<Enumerator: ...>. I'm not really sure what is happening. If anyone could explain to me what is going on that would be very helpful.

jkeuhlen
  • 4,401
  • 23
  • 36
user3746602
  • 433
  • 1
  • 6
  • 15

1 Answers1

1

From the documentation:

Invokes the given block once for each element of self, replacing the element with the value returned by the block.

See also Enumerable#collect.

If no block is given, an Enumerator is returned instead.

This means that if you have used map! with a block - the array would have replaced all its elements with the return value of the block:

b.map(&:values).uniq!.map!(&:first)
# => ["us", "au", "fr", "mx", "ad"]

Since you did not add a block, you got an Enumerator, which is like a delayed action cursor, where you can add your block later on:

enum = b.map(&:values).uniq!.map!
enum.each(&:first)
# => ["us", "au", "fr", "mx", "ad"]
Community
  • 1
  • 1
Uri Agassi
  • 36,848
  • 14
  • 76
  • 93