I have a string that's been imported from a csv such as:
14th Aug 2009:1, 15th Aug 2009:1, 16th Sep 2015:1|Style1, 17th Sep 2015:1|Style 1
I wish to add this data to my database in a specific way. First I split it on , to get each date group (in this case 4 dates).
Secondly i'd like a way to split each of those date groups into multiple segments. The first with the date, second with the number after the colon and then a varied amount more for each of the items separated by the | character.
Is there an decent efficient way to accomplish this in Ruby?
Looking for outcome to be a hash like so:
{ '14th Aug 2009' => 1, '15th Aug 2009' => 1, '16th Aug 2009' => 1, '16th Sep 2015' => { 1 => 'Style 1' }, '17th Sep 2015' => { 1 => 'Style 1' }
Basically if the string was like so:
15th Aug 2009:1, 16th Sep 2015:3|Style1|Style 1, 17th Sep 2015:1|Style 1
I would get
{ '15th Aug 2009' => 1, '16th Sep 2015' => { '', 'Style 1', 'Style 1' }, '17th Sep 2015' => { 1 => 'Style 1' }
Basically, the text separated by |'s should be assigned to the number after the colon. If the number is 3 and there are two sets of text after it then one is an empty string and the other two will say the text (eg: "Style 1".
Sorry for sounding very confusing.
{ '', 'Style 1', 'Style 1' }. Do you mean to use an array instead? Like:[ '', 'Style 1', 'Style 1' ]?string.split(", ").each_with_object({}) { |line, hsh| k, *tokens = line.split(/:|\|/); hsh[k] = tokens }should do the trick