Created
August 16, 2012 13:47
-
-
Save msapariya/3370217 to your computer and use it in GitHub Desktop.
ruby hash from text para
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" | |
# | |
# A utility to get hash out of the text block | |
# | |
# Every line is delimited by ls == line separator | |
# Records in lines are delimited by rs = record separator | |
# | |
# The hash is returned where key is the first record and | |
# value is array of rest of the values | |
# | |
# Filter the records that interests you by specifying regular | |
# expression. By default no filtering will be done. | |
# | |
# All white spaces are compressed to no spaces or single spaces | |
# based on the record separator. | |
# | |
def columnize(ls,rs,input,re=nil) | |
outhash={} | |
wscompressor = (rs == " " ? " " : "") | |
lines=input.split(ls) | |
lines.each {|line| | |
next unless line.match(re) if re | |
line.gsub!(/\s+/, wscompressor) | |
outhash[line.split(rs)[0]] = line.split(rs)[1..-1] | |
} | |
outhash | |
end | |
inputstring=<<INPUT_STRING | |
Some text which do not have record separator | |
Some more text with record separator : that I use in sample | |
did : 3 | |
total_size_MB : 204800.0 | |
used_size_MB : 8326.8 | |
INPUT_STRING | |
puts "=====Input String==========" | |
puts "#{inputstring}" | |
puts "=====Extract fields matchin 'total' or 'used' ==========" | |
pp columnize("\n", ":", inputstring, /total|used/i) | |
puts "=====Extract all fields ==========" | |
pp columnize("\n", ":", inputstring) | |
puts "===============" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment