我有一个哈希值
{1=>true, 7=>false, 6=>true, 4=>false}
或者一个类似的数组
[1, true], [7, false], [6, true], [4, false]]
或者
[true, false, true, false]
.
如何找到数组中 true
的个数?
我有一个哈希值
{1=>true, 7=>false, 6=>true, 4=>false}
或者一个类似的数组
[1, true], [7, false], [6, true], [4, false]]
或者
[true, false, true, false]
.
如何找到数组中 true
的个数?
Hash
会产生两个元素的Array
,因此前两个元素实际上是完全相同的。{ 1 => true, 7 => false, 6 => true, 4 => false }.count(&:last)
[[1, true], [7, false], [6, true], [4, false]].count(&:last)
对于简单的Array
情况,你可以像这样做:
[true, false, true, false].count(true)
当然,这个 Array
与您上面的 Hash
的 Hash#values
相同,因此您也可以在其上使用相同的方法:
{ 1 => true, 7 => false, 6 => true, 4 => false }.values.count(true)
如果你不知道你将得到其中的哪一个,你可以使用类似这样的代码:
{ 1 => true, 7 => false, 6 => true, 4 => false }.flatten.count(true)
[[1, true], [7, false], [6, true], [4, false]].flatten.count(true)
[true, false, true, false].flatten.count(true)
使用Enumerable#count方法:
hash.values.count(true)
array_of_pairs.map { |k, v| v }.count(true)
plain_array.count(true)
更冗长,但不会创建中间数组:
hash_or_array_of_pairs.inject(0) { |acc, (k, v)| acc + (v == true ? 1 : 0) }
更简单:
hash.values.count(true)
array.flatten.count(true)
这适用于上述所有情况。
Hash[array].values.count(true)
。 - Mark Thomas关于哈希:
{ :a => true, :b => true, :c => false }.select{ |k,v| v }.length
=> 2
对于数组:
[true, false, false, true, true].select{ |o| o }.length
=> 3
另一种方法(使用否定进行测试):
[true, false, false, true, true].reject{ |o| o != true }.length
=> 3
.to_a
才能使其工作):[[1, true], [7, false], [6, true], [4, false]].flatten.select{|s| s == true }.size
s == true
可以简化为 s
。 - Cadoiz哈希:
my_hash.values.select(&:present?).size
my_2d_array.map(&:last).select(&:present?).size
或
my_2d_array.select { |_first, last| last.present? }.size
一维数组:
array.select(&:present?).size
values_of_hash = {1=>true, 7=>false, 6=>true, 4=>false}.values # also works with the `.map` command from the line below
values_of_array_of_pairs = [[1, true], [7, false], [6, true], [4, false]].map { |k, v| v } # or the `.inject` command from this answer: https://dev59.com/rG855IYBdhLWcg3wMBLV#4488905
values_of_2d = [[1, true], [7, false], [6, true], [4, false]].map(&:last) # similar idea from https://dev59.com/rG855IYBdhLWcg3wMBLV#4490032
values_of_2d = {1=>true, 7=>false, 6=>true, 4=>false}.map(&:last) # both a hash and an array of pairs hold the second value in `.last`
values_of_array = [true, false, true, false]
def my_tally(values)
Set.new(values).map {|unique_value| [unique_value, values.count(unique_value)]}
end
# replace `_xy` with anything of the above like e.g. `_array`
my_tally values_of_xy
# => [[true, 2], [false, 2]]
values_of_xy = {1=>:banana, 2=>:cherry, 3=>:apple, 4=>:cherry, 5=>:banana, 6=>:cherry}.values
my_tally values_of_xy
# => [[:banana, 2], [:cherry, 3], [:apple, 1]]
对于 Ruby 2.7+ 版本来说, 你显然应该使用 tally。