I'm building a script to read and parse markdown files in Ruby. The script needs to be able to read and understand the multimarkdown header information at the top of the files so that it can perform additional actions on the output.
The header values look like this:
Title: My Treatise on Kumquats
Author: Joe Schmoe
Author URL: http://somedudeswebsite.me/
Host URL: http://googlesnewthing.com/
Created: 2012-01-01 09:41
I can't figure out how to split the lines of text into a simple key-value dictionary. The built in split function doesn't seem to work in this case because I only want it to split on the first occurrence of a colon (:) in each line. Additional colons would be part of the value string.
In case it matters I'm using Ruby 1.8.7 on OS X.
This does it:
s = <<EOS
Title: My Treatise on Kumquats
Author: Joe Schmoe
Author URL: http://somedudeswebsite.me/
Host URL: http://googlesnewthing.com/
Created: 2012-01-01 09:41
EOS
h = Hash[s.each_line.map { |l| l.chomp.split(': ', 2) }]
p h
Output:
{"Title"=>"My Treatise on Kumquats", "Author"=>"Joe Schmoe", "Author URL"=>"http://somedudeswebsite.me/", "Host URL"=>"http://googlesnewthing.com/", "Created"=>"2012-01-01 09:41"}
Use split
with an optional second parameter (thanks to @MichaelKohl)
s = 'Author URL: http://somedudeswebsite.me/'
key, value = s.split ': ', 2
puts key
puts value
Output
Author URL
http://somedudeswebsite.me/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With