RubyFlow The Ruby and Rails community linklog

×

The Ruby and Rails community linklog

Made a library? Written a blog post? Found a useful tutorial? Share it with the Ruby community here or just enjoy what everyone else has found!

Unpacking arr.max_by &arr.tally

A one-liner from Ruby Weekly #828 returns the most frequent element in an array. This post unpacks why it works: & calls to_proc, and a Hash’s to_proc is a key lookup, which also means it quietly returns nil for missing keys. It also benchmarks the “faster” rewrite, arr.tally.max_by(&:last): 2.2x faster with many duplicates, 1.4x slower when most elements are unique, with allocation counts showing why.

Post a comment

You can use basic HTML markup (e.g. <a>) or Markdown.

As you are not logged in, you will be
directed via GitHub to signup or sign in