-
-
Save 3limin4t0r/24634f683c9c33872bbe4916250b12a0 to your computer and use it in GitHub Desktop.
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 '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(®ex.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