计数ruby正则表达式匹配

时间:2017-01-28 23:57:43

标签: arrays ruby count

我正在寻找数组的计数/长度。 匹配aip然后count = 4匹配bip count = 5 这些计数可能每次都有所不同,主机的值可能是3到n。所以我试图从长度上打电话。

hosts = ["aip1,aip2,aip3,aip4","bip1,bip2,bip3,bip4,bip5"]

if ! hosts.nil?
  hosts.each do|d|
  if d.match(/^aip/)
      name = "a"
    else
      name = "b"
    end

我试过这样,不适合我,有没有更好的方法我可以尝试。得到数数。

i was using counts = Hash.new(0)
hosts.each { |count| counts[count] += 1 }

我试图得到的确如此,如果匹配regexp aip然后count = 4或者count必须得到5(我有5个bip) 这些计数数字每次都会改变。 使用ruby 2.0.0p648(2015-12-16)[x86_64-linux]版本ruby

1 个答案:

答案 0 :(得分:1)

目前尚不清楚你要做什么,而且你好像在询问XY Problem

我建议使用类似的东西来分解字符串数组:

hosts = ["aip1,aip2,aip3,aip4","bip1,bip2,bip3,bip4,bip5,....."]

hash = hosts.map { |s| [ s[0], s.split(',') ] }.to_h
# => {"a"=>["aip1", "aip2", "aip3", "aip4"],
#     "b"=>["bip1", "bip2", "bip3", "bip4", "bip5", "....."]}

此时hash可以轻松找到答案:

hash.keys # => ["a", "b"]

hash['a'] # => ["aip1", "aip2", "aip3", "aip4"]
hash['a'].size # => 4

甚至确定count

count = hash.values.map(&:size).reduce(&:+) # => 10

分解为:

count = hash.values      # => [["aip1", "aip2", "aip3", "aip4"], ["bip1", "bip2", "bip3", "bip4", "bip5", "....."]]
            .map(&:size) # => [4, 6]
            .reduce(&:+) # => 10

如果你使用的是Ruby 2.4+,你可以使用:

count = hash.values.sum { |i| i.size } # => 10
相关问题