views:

63

answers:

4

Say I have an array like this:

["white", "red", "blue", "red", "white", "green", "red", "blue", "white", "orange"]

I want to go through the array and create a new array containing each individual color and the amount of times it appeared in the original array.

So, in the new array it would report that "white" appeared 3 times, "blue" appeared 2 times and so on...

How should I go about doing this?

+3  A: 
counts = Hash.new(0)
colors.each do |color|
    counts[color] += 1
end
sepp2k
+1 for a simple answer to a simple question.
Mark Byers
Okay, this looks good. How would I go about printing out the value of the counts hash in order of largest to smallest?
Michael Berkompas
@Micheal: Just use `sort_by {|color, count| -count}` on the resulting hash to get an array sorted by decreasing count.
sepp2k
Never mind, I got it.
Michael Berkompas
Great, your solution was cleaner than the one I found.
Michael Berkompas
Why the downvote?
sepp2k
+5  A: 

better return a hash...

def arr_times(arr)
  arr.inject(Hash.new(0)) { |h,n| h[n] += 1; h }
end
amikazmi
A: 
result = {}
hash = array.group_by{|item| item}.each{|key, values| result[key] = values.size}
p result
aaz
+1  A: 

I see you tagged the question with ruby-on-rails.

If this is a database model/column (e.g., User model with color attribute) you should be doing the computation in the DB:

 User.count(:all,:group=>:color).sort_by {|arr| -arr[1]}
klochner