DEV Community

matt swanson
matt swanson

Posted on • Originally published at boringrails.com on

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

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.

Usage

The uniq method operates on an enumerable and compresses your data down to unique values.

Outreach::Task.all.map(&:status).uniq
=> ["Confirmed w/o Outreach",
 "Awaiting Outreach",
 "Responded",
 "No Response Expected",
 "Follow-up",
 "Awaiting Reply"]
Enter fullscreen mode Exit fullscreen mode

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.

Outreach::Task.all.map(&:status).tally
=> {"Confirmed w/o Outreach"=>106,
 "Awaiting Outreach"=>28,
 "Responded"=>48,
 "No Response Expected"=>10,
 "Follow-up"=>4,
 "Awaiting Reply"=>8}
Enter fullscreen mode Exit fullscreen mode

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


Top comments (0)