How can I get the number of value instances in a Rails array?

Say I have an array like this:

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

I want to go through an array and create a new array containing each individual color, and the number of times it appears in the original array.

So, in the new array it will be indicated that β€œwhite” appeared 3 times, β€œblue” appeared 2 times and so on ...

How should I do it?

+3
source share
4 answers
counts = Hash.new(0)
colors.each do |color|
    counts[color] += 1
end
+3
source

better to return the hash ...

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

, ruby-on-rails.

/ (, ), :

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

Source: https://habr.com/ru/post/1733949/


All Articles