Boring Rails

Tip: Quickly explore your data with `uniq` and `tally`

:fire: Tiny Tips

A common question you may want to answer on user-input data is: what values have been entered and how many times is each one used?

Maybe you have a list of dropdown options and you want to investigate removing a rare-used option.

Ruby has two handy methods that I reach for often: uniq and tally.


The uniq method operates on an enumerable and compresses your data down to unique values.
=> ["Confirmed w/o Outreach",
 "Awaiting Outreach",
 "No Response Expected",
 "Awaiting Reply"]

While most developers are familiar with uniq, the tally method is one of the best kept secrets in Ruby. The tally method takes an enumerable of values and returns a hash where the keys are unique values and the values are the number of times the value appeared in the list.
=> {"Confirmed w/o Outreach"=>106,
 "Awaiting Outreach"=>28,
 "No Response Expected"=>10,
 "Awaiting Reply"=>8}

These two methods are great to have in your toolbox to quickly explore your data in a Rails console.

Additional Resources

Ruby API: Enumerable#uniq

Ruby API: Enumerable#tally

If you like these tips, you'll love my Twitter account. All killer, no filler.