我想计算数组中包含数字的参数。
array = ['Cat', '3Dog', 'Fish', 'Horse5']
=> "There is two arguments containing numbers"
答案 0 :(得分:3)
您可以传递参数以使其与任何模式的单词匹配的方式进行计数。
array = ["Cat", "3Dog", "Fish", "Horse5"]
puts array.count {|x| x.match /[0-9]/ } # this will output 2.
答案 1 :(得分:3)
您可以通过关注获得
array = ["Cat", "3Dog", "Fish", "Horse5"]
array.count { |x| x =~ /\d/ }
# => 2
# even another form can be used also
array.count(&/\d/.method(:=~))
# => 2
答案 2 :(得分:2)
通过使用grep命令
array = ["Cat", "3Dog", "Fish", "Horse5"]
2.2.9 :021 > array.grep(/\d/)
=> ["3Dog", "Horse5"]
2.2.9 :022 > array.grep(/\d/).count
=> 2