1

Model.find_by_tag_name("#foo") returns an array with:

  • 25 records with tag_name = "#foo"
  • 40 records with tag_name = "#foobar"
  • 15 records with tag_name = "#foobarbaz"

I want to count the number of times each unique tag_name showed up, sort the results by that count, then eliminate duplicates. The resulting order should be:

  1. #foobar
  2. #foo
  3. #foobarbaz

Currently I'm doing something like this to get the uniques and a count:

counter = Hash.new(0)
uniques = results.each{|tag| counter[tag.tag_name] += 1 }.uniq{|tag| tag.tag_name }

The above makes counter => {"#foo"=>25, "#foobar"=>40, "#foobarbaz"=>15}.

Having retrieved, de-duped and counted the results, what approaches might I take to sorting the resulting array of unique tags(uniques) by the number of times they showed up?

1 Answer 1

2
{"#foo"=>25, "#foobar"=>40, "#foobarbaz"=>15}.sort_by { |k, v| -v }.map(&:first)
Sign up to request clarification or add additional context in comments.

2 Comments

I should have been more clear- I don't want to sort counter, but rather the array of unique results.
@ChrisCashwell did you even run the code? Ross’s first answer does return what you are looking for.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.