Reputation: 2804
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?
Upvotes: 0
Views: 141
Reputation: 160551
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
.
Upvotes: 2