Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby-on-rails-4/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays RubyonRails——如何知道同一对象在使用活动记录的数组中出现了多少次?_Arrays_Ruby On Rails 4_Activerecord - Fatal编程技术网

Arrays RubyonRails——如何知道同一对象在使用活动记录的数组中出现了多少次?

Arrays RubyonRails——如何知道同一对象在使用活动记录的数组中出现了多少次?,arrays,ruby-on-rails-4,activerecord,Arrays,Ruby On Rails 4,Activerecord,如何知道同一对象在数组中出现的次数? 我想检查我找到该对象的次数,如: array = ['A','A','A','B','B','C','C','C','D'] 所以,A出现了三次,B出现了两次,C也出现了三次,D只出现了一次 我知道如果我使用“查找所有”,比如: 我会得到答案的 ["A", "A", "A", "B", "B", "C", "C", "C"] 但是,我怎么能数呢?我想要像这样的东西: A = 3, B = 2, C = 3, D = 1. 您可以在数组上使用injec

如何知道同一对象在数组中出现的次数? 我想检查我找到该对象的次数,如:

array = ['A','A','A','B','B','C','C','C','D']
所以,A出现了三次,B出现了两次,C也出现了三次,D只出现了一次

我知道如果我使用“查找所有”,比如:

我会得到答案的

["A", "A", "A", "B", "B", "C", "C", "C"]
但是,我怎么能数呢?我想要像这样的东西:

 A = 3, B = 2, C = 3, D = 1.

您可以在数组上使用inject来迭代数组,并在每次迭代中传递一个散列来存储数据。因此,要检索给定数组的计数,请执行以下操作:

array = ["A", "A", "A", "B", "B", "C", "C", "C"]
array.inject(Hash.new(0)) do |hash, array_item| 
  hash[array_item] += 1
  hash # this will be passed into the next iteration as the hash parameter
end

=> {"A"=>3, "B"=>2, "C"=>3}
传入
Hash.new(0)
而不是
{}
将意味着您第一次遇到的每个键的默认值将是0

array = ["A", "A", "A", "B", "B", "C", "C", "C"]
array.inject(Hash.new(0)) do |hash, array_item| 
  hash[array_item] += 1
  hash # this will be passed into the next iteration as the hash parameter
end

=> {"A"=>3, "B"=>2, "C"=>3}