Skip to content

Instantly share code, notes, and snippets.

@3limin4t0r
Last active September 30, 2019 14:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 3limin4t0r/24634f683c9c33872bbe4916250b12a0 to your computer and use it in GitHub Desktop.
Save 3limin4t0r/24634f683c9c33872bbe4916250b12a0 to your computer and use it in GitHub Desktop.
require 'yaml'
prefixes = { 'tel' => 'Tel.: ', 'fax' => 'Fax: ', 'email' => 'E-Mail: ', 'website' => 'Website: ' }
regexes = prefixes.transform_values { |prefix| /\A#{Regexp.escape(prefix)}/ }
contacts = []
File.open('/path/to/data.txt') do |data|
# If a zero-length record separator is supplied, the string is split
# into paragraphs delimited by multiple successive newlines.
# https://ruby-doc.org/core-2.6.4/String.html#method-i-each_line
data.each_line('') do |contact_text|
# split the paragraph into lines, chomp the newline character at the end and remove empty values
contact_lines = contact_text.each_line("\n", chomp: true).reject(&:empty?)
contact = { 'name' => contact_lines.shift, 'address' => contact_lines.shift }
regexes.each do |key, regex|
index = contact_lines.find_index(&regex.method(:match?))
contact[key] = (contact_lines.delete_at(index).sub(regex, '') if index)
end
contacts << contact
end
end
File.open('/path/to/data.yaml', 'w+') { |file| file.write(contacts.to_yaml) }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment