我有一段代码,可以在一段时间内获取签到列表。请参阅下面的代码。
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}
答案 0 :(得分:1)
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}
答案 1 :(得分:0)
从哈希中获取值:
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
答案 2 :(得分:0)
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}