Hacker News new | ask | show | jobs
by rubyfan 2374 days ago
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.

1 comments

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"]