按值对散列进行分组并获取 Rails 中一组下的值的计数
Grouping hash by value and get count of the values under one group in Rails
我有一个代码可以获取给定时间跨度的签到列表。请参阅下面的代码。
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)
然后代码会给我所有满足给定条件的签入对象。我需要做的下一件事是对每个客户的签到列表进行分组。所以我有这段代码可以做到这一点。
group_customer_id = customer_checkins.group(:customer_id).count
然后按客户 ID 对其进行分组将生成一个散列。请参阅下面的示例。
{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}
我现在想获得具有相同签到次数的客户数量 - 有多少客户有 9 次签到、5 次签到等。所以给出上面的哈希值。我期待这样的输出:
{9 => 1, 8=> 1, 5 => 1, 4=> 3, 3 => 4, 2=> 1, 1 => 3}
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}
从哈希中获取值,例如:
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
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}
我有一个代码可以获取给定时间跨度的签到列表。请参阅下面的代码。
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)
然后代码会给我所有满足给定条件的签入对象。我需要做的下一件事是对每个客户的签到列表进行分组。所以我有这段代码可以做到这一点。
group_customer_id = customer_checkins.group(:customer_id).count
然后按客户 ID 对其进行分组将生成一个散列。请参阅下面的示例。
{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}
我现在想获得具有相同签到次数的客户数量 - 有多少客户有 9 次签到、5 次签到等。所以给出上面的哈希值。我期待这样的输出:
{9 => 1, 8=> 1, 5 => 1, 4=> 3, 3 => 4, 2=> 1, 1 => 3}
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}
从哈希中获取值,例如:
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
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}