Reputation: 43
I have a code that gets the list of checkins given a span of time. See code below.
from = Time.zone.now.beginning_of_month
to = Time.zone.now.end_of_month
customer_checkins = CustomerCheckin.where(account_id: seld.id, created_at: from..to)
The code would then give me all checkin objects that satisfies the given condition. The next thing that I need to do is to group the list of checkins per customer. So I have this code to do that.
group_customer_id = customer_checkins.group(:customer_id).count
Grouping it by customer id will then result to a hash. See example below.
{174621=>9,180262=>1,180263=>1,180272=>1,180273=>3,180274=>3,180275=>4,180276=>3,180277=>2,180278=>4,180279=>4,180280=>3,180281=>5,180282=>8}
I would like now to get the count of customers with the same checkin count - how many customers have 9 checkins, 5 checkins, etc. So given the hash above. I am expecting an output like this:
{9 => 1, 8=> 1, 5 => 1, 4=> 3, 3 => 4, 2=> 1, 1 => 3}
Upvotes: 1
Views: 348
Reputation: 1705
a = {174621=>9,180262=>1,180263=>1,180272=>1,180273=>3,180274=>3,180275=>4,180276=>3,180277=>2,180278=>4,180279=>4,180280=>3,180281=>5,180282=>8}
result = a.map{|k,v| v}.each_with_object(Hash.new(0)) { |word,counts| counts[word] += 1 }
# => {9=>1, 1=>3, 3=>4, 4=>3, 2=>1, 5=>1, 8=>1}
Upvotes: 0
Reputation: 4271
Get the values from hash like:
customer_array = {174621=>9,180262=>1,180263=>1,180272=>1,180273=>3,180274=>3,180275=>4,180276=>3,180277=>2,180278=>4,180279=>4,180280=>3,180281=>5,180282=>8}.values
customer_count = Hash.new(0)
customer_array.each do |v|
customer_count[v] += 1
end
puts customer_count
Upvotes: 0
Reputation: 29174
h.each_with_object({}) {|(k,v), h| h[v] = h[v].to_i + 1}
# => {9=>1, 1=>3, 3=>4, 4=>3, 2=>1, 5=>1, 8=>1}
Upvotes: 1