DEV Community

matt swanson
matt swanson

Posted on • Originally published at boringrails.com on

6 1

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


Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More