从Ruby字符串中提取信息

我在远程设备上有一个与此类似的文本文件:

D0-23-DB-31-04-3E%20192.168.4.42%20dnat 68-A8-6D-0C-38-B2%20192.168.4.40%20dnat 

我创建了一个小的Ruby脚本来将其转换为字符串并将其发布到我的Rails应用程序:

  def chilli_list hash = File.open("/tmp/client_list", "rb").read return hash end 

然后输出如下:

 "D0-23-DB-31-04-3E%20192.168.4.42%20dnat\n68-A8-6D-0C-38-B2%20192.168.4.40%20dnat\n" 

我需要逐位提取信息并在视图中显示。 到目前为止,我还没有走得太远。 我尝试了以下哪个是好的:

 str = "D0-23-DB-31-04-3E%20192.168.4.42%20dnat\n68-A8-6D-0C-38-B2%20192.168.4.40%20dpass\n" str.each_line do |line| puts line.split(" ").first puts line.split(" ").second end 

这是最好的方式还是有更好的方法?

最后也是最重要的是,我还需要对字符串执行一些计算。 我可以使用str.lines.count计算行str.lines.count ,但我需要的是第三个值== nat的行的计数,如上例所示。

我该怎么办呢?

首先,这里是如何将HTML编码转换回普通字符串:

 require 'uri' URI.decode('D0-23-DB-31-04-3E%20192.168.4.42%20dnat') # => "D0-23-DB-31-04-3E 192.168.4.42 dnat" 

以下是如何将整个字符串分解为单独的解码行:

 "D0-23-DB-31-04-3E%20192.168.4.42%20dnat\n68-A8-6D-0C-38-B2%20192.168.4.40%20dnat\n".split("\n") .map{ |l| URI.decode(l) } 

这导致IRB中的这个数组:

 [ [0] "D0-23-DB-31-04-3E 192.168.4.42 dnat", [1] "68-A8-6D-0C-38-B2 192.168.4.40 dnat" ] 

添加.count{ |l| l[/ dnat$/] } .count{ |l| l[/ dnat$/] }到上一个命令的末尾,你将有你的计数:

 "D0-23-DB-31-04-3E%20192.168.4.42%20dnat\n68-A8-6D-0C-38-B2%20192.168.4.40%20dnat\n".split("\n") .map{ |l| URI.decode(l) } .count{ |l| l[/ dnat$/] } 

返回2

您也可以通过直接计算'nat'出现次数来简化整个过程:

 "D0-23-DB-31-04-3E%20192.168.4.42%20dnat\n68-A8-6D-0C-38-B2%20192.168.4.40%20dnat\n".scan('nat').count 

哪个也返回2