Created
February 14, 2013 03:23
-
-
Save zerowidth/4950374 to your computer and use it in GitHub Desktop.
Script to parse a text table and convert to a reasonable output. Demonstration of an idiomatic ruby script for a friend.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require "pp" | |
def convert_to_offsets(widths) | |
offsets = [] | |
position = 0 | |
widths.each.with_index do |width, index| | |
offsets << (position...(width+position)) # range does not include the end | |
position += width + 1 # assume spacing of 1 character | |
end | |
offsets | |
end | |
def extract_values(line, offsets) | |
offsets.map { |range| line[range].strip } | |
end | |
def read_table(table) | |
lines = table.split "\n" | |
fields = lines[0].split /\s+/ | |
widths = lines[1].split(" ").map(&:length) | |
offsets = convert_to_offsets widths | |
lines[2..-1].map do |line| | |
values = extract_values line, offsets | |
Hash[*fields.zip(values).flatten] | |
end | |
end | |
# this reads from the bottom of the file, after the __END__: | |
DATA.read.split("***\n").each do |table| | |
puts "-" * 20 | |
data = read_table table | |
data.each do |row| | |
# do a bit o' massaging with the data before displaying it: | |
port_id = row.delete "Port" | |
row["PortID"] = port_id | |
row["Module"], row["PortNum"] = port_id.split("/").map(&:to_i) | |
pp row | |
end | |
end | |
__END__ | |
Port Name Status Vlan Duplex Speed Type | |
----- -------------------- ---------- ---------- ------ ----- ------------ | |
1/1 LcacdcC1-CU08 7/12 connected trunk full 1000 1000Base SX | |
1/2 disable 1 full 1000 1000Base SX | |
3/1 not used? to 8/12 connected trunk full 1000 1000BaseSX | |
*** | |
Port Name Status Vlan Duplex Speed Type | |
----- ----------------- ---------- ------------ ------ ----- ------------ | |
1/1 Lcac1-CU08 7/12 connected trunk full 1000 1000BaseSX | |
1/2 disable 1 full 1000 1000 BaseSX | |
3/1 nosed? to 8/12 connected trunk full 1000 1000 BaseSX |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Aaaand because I appear to have nothing better to do, let's go so far overboard we can't see the boat anymore. Here's an example of that script extracted into a class and documented with TomDoc.
And the script: