Hacker News new | ask | show | jobs
by tyingq 2375 days ago
Does the pattern matching do something that Ruby's map() can't do?

Coming from Perl, map() there can return fewer elements than the source list, so pattern matching works already. A short skim of Ruby's map seems to imply it always returns something with the same number of elements.

Edit: I was confused about what this feature did. So this subthread is still interesting, but mostly unrelated.

2 comments

Yeah afaik something is always returned from the block (even if it’s nil). Occasionally I recall my self doing something where the block might return nil and then I’d call `compact` to get rid of extra nil stuff. It works when you want a modified version of the enumerable but don’t want nil stuff. If you just want to match a subset then I think `select` is probably what you want.

Further, the pattern matching feature is significantly different than `map` imo.

In JavaScript, Elixir, and Ruby I use flatMap for this purpose. You can return an empty array on the block to “skip” over the element.
2.7 introduces `Enumerable#filter_map` for that. Example from the NEWS file:

[1, 2, 3].filter_map {|x| x.odd? ? x.to_s : nil } #=> ["1", "3"]

Map is data manipulation, whereas pattern-matching is control flow.
Yes, thank you. Reading the sub linked presentation, I see it now.

The sentence "It can traverse a given object and assign its value if it matches a pattern" sounded like traverse and (optionally) manipulate.