如何将文本拆分为键值对?

kdm*_*ray 3 ruby string parsing

我正在构建一个脚本来读取和解析Ruby中的markdown文件.该脚本需要能够读取和理解文件顶部的multimarkdown标头信息,以便它可以对输出执行其他操作.

标头值如下所示:

Title: My Treatise on Kumquats
Author: Joe Schmoe
Author URL: http://somedudeswebsite.me/
Host URL: http://googlesnewthing.com/
Created: 2012-01-01 09:41
Run Code Online (Sandbox Code Playgroud)

我无法弄清楚如何将文本行分成一个简单的键值字典.内置拆分功能在这种情况下似乎不起作用,因为我只希望它在每行中第一次出现冒号(:)时拆分.额外的冒号将是值字符串的一部分.

如果重要的是我在OS X上使用Ruby 1.8.7.

Mic*_*ohl 7

这样做:

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
Run Code Online (Sandbox Code Playgroud)

输出:

{"Title"=>"My Treatise on Kumquats", "Author"=>"Joe Schmoe", "Author URL"=>"http://somedudeswebsite.me/", "Host URL"=>"http://googlesnewthing.com/", "Created"=>"2012-01-01 09:41"}
Run Code Online (Sandbox Code Playgroud)


Ser*_*sev 6

使用split可选的第二个参数(感谢@MichaelKohl)

s = 'Author URL: http://somedudeswebsite.me/'
key, value = s.split ': ', 2
puts key
puts value
Run Code Online (Sandbox Code Playgroud)

产量

Author URL
http://somedudeswebsite.me/
Run Code Online (Sandbox Code Playgroud)

  • @SergioTulentsev:`split`有一个可选的第二个参数,用于指定拆分后你想要的最大部件数:`''作者URL:http://somedudeswebsite.me/'".split(':',2)# => ["'作者URL","http://somedudeswebsite.me /'"]` (2认同)