Extracting Information from a Ruby String

瘦欲@ 提交于 2019-12-13 05:58:55

问题


I have a text file similar to this on a remote device:

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

I created a small Ruby script to convert this to a string and post it to my Rails application:

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

The output then looks like:

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

I need to extract the information bit by bit and display in a view. So far, I've not got far. I tried the following which is OK:

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

Is that the best way to do it or is there a better way?

Finally and most importantly, I also need to perform a few calculations on the string. I can count the lines with str.lines.count, but what I need is a count of the lines where the third value == nat as in the example above.

How can I go about that?


回答1:


First, here's how to convert from HTML encoding back into a normal string:

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"

Here's how to break the entire string into separate decode lines:

"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) }

which results in this array in 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"
]

Add on .count{ |l| l[/ dnat$/] } to the end of the previous command and you'll have your count:

"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$/] }

Which returns 2.

You could also probably simplify the whole process by just directly counting the number of 'nat' occurrences:

"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

Which also returns 2.



来源:https://stackoverflow.com/questions/11959047/extracting-information-from-a-ruby-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!