We take an iterator on separate lines (so as not to store the entire broken array in the memory, but to take the podstvorochki one by one; this is often saving on matches, but it can have a good effect on a huge data set):
str.each_line
And we try to shove each line into an empty hash ...
.each_with_object({}) do |line, hash|
...in the following way:
We get the key and value from the line (cutting off the spaces: I think this is useful here):
key, value = line.split(':', 2) # Разбить по двоеточию не более чем на 2 части .map(&:strip) # Подстричь оба от пробельных символов # Ура декомпозиции! # `a, b = [1, 2]` то же, что и `a = 1; b = 2`
And if the value found (not nil , which can be for strings without : , we push it into our hash:
hash[key] = value unless value.nil?
It's all over.
end
The return value will be the desired hashmap.
Of course, this is Ruby, and you can make many different variations on the subject. Say, if you want to do some postprocessing value, instead of wrapping most of the block in unless value.nil? , can I do next if value.nil? , and the remainder of the block will be simply omitted in the case of an missing value.