The Crystal Programming Language Forum

Ruby 2.7 new Enumerable methods

Ruby 2.7 adds a couple of new methods to Enumerable:

  • Enumerable#filter_map. For example: (1..10).filter_map { |i| i * 2 if i.even? } # => [4, 8, 12, 16, 20]. This is useful to avoid having to do .select { ... }.map { ... } which creates an intermediate array and it’s a very common idiom in functional languages (like Haskell and Elm).
  • Enumerable#tally. For example ['a', 'b', 'a', 'b', 'b'].tally # => {'a' => 2, 'b' => 3}. Counting things is pretty common, I think.

Should we add these to Crystal? They seem easy to implement and generally useful.

1 Like

For Enumerable#filter_map we already have Enumerable#compact_map which does just that!


tally is nice, i’ve even used such function few times.
But I have to say that (as non-native speaker) never heard this word so would never guess this name. Maybe it’s just me.

1 Like

I agree. The same happened to me too. I think Ruby chose that name because chances of it colliding with a user-defined method named like that is very unlikely.

1 Like

tally seems like a fine name to me, as an american (although I suspect it’s more widely used in England than the USA). As soon as I saw the method name, I knew what it was going to do.

On the other hand, it does seem to be true that I’ve never thought to use it in any program I’ve written, even though I have quite a few programs which have tallied things up like that!

For me at least, I think the name of filter_map is somewhat better than compact_map. And it’s one character shorter! :slight_smile: