当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Ruby Array count()用法及代码示例


Array#count():count()是一个Array类方法,它返回数组中元素的数量。它还可以找到数组中特定元素的总数。

用法: Array.count()

参数:  obj - specific element to found

返回: removes all the nil values from the array. 

代码#1:count()方法示例

# Ruby code for count() method 
# to count elements 
  
# declaring array 
a = [18, 22, 33, nil, 5, 6] 
  
# declaring array 
b = [1, 4, 1, 1, 88, 9] 
  
# declaring array 
c = [18, 22, nil, nil, 50, 6] 
  
# counting total elements 
puts "counting:#{a.count}\n\n"
  
# counting 1 
puts "counting:#{b.count(1)}\n\n"
  
# counting 'nil' 
puts "counting:#{c.count(nil)}\n\n"

输出:


counting:6

counting:3

counting:2

代码2:count()方法示例

# Ruby code for count() method 
# to count elements 
  
# declaring array 
a = ["abc", "nil", "dog"] 
  
# declaring array 
b = ["cow", nil, "dog"] 
  
# declaring array 
c = ["cat", nil, nil] 
  
# counting total elements 
puts "counting:#{a.count}\n\n"
  
# counting 1 
puts "counting:#{b.count(1)}\n\n"
  
# counting 'nil' 
puts "counting:#{c.count(nil)}\n\n"

输出:

counting:3

counting:0

counting:2


相关用法


注:本文由纯净天空筛选整理自mayank5326大神的英文原创作品 Ruby | Array count() operation。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。