Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I split text into key-value pairs?

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.

like image 426
kdmurray Avatar asked Dec 03 '22 05:12

kdmurray


2 Answers

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"}
like image 87
Michael Kohl Avatar answered Dec 24 '22 00:12

Michael Kohl


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/
like image 31
Sergio Tulentsev Avatar answered Dec 24 '22 02:12

Sergio Tulentsev