0

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.

3
  • Can you give an example of what the output should be? What have you tried so far? Commented Mar 3, 2016 at 21:19
  • 1
    Your example output format is not valid: { '', 'Style 1', 'Style 1' }. Do you mean to use an array instead? Like: [ '', 'Style 1', 'Style 1' ]? Commented Mar 3, 2016 at 23:06
  • string.split(", ").each_with_object({}) { |line, hsh| k, *tokens = line.split(/:|\|/); hsh[k] = tokens } should do the trick Commented Mar 4, 2016 at 0:38

1 Answer 1

1

I'm assuming that you meant for the '|' separted items to build an Array, as infused asked about. How about this?

s ="15th Aug 2009:1, 16th Sep 2015:3|Style1|Style 1, 17th Sep 2015:1|Style 1"
result = {}
s.split(',').each do |v|
  date,rest = v.split(':')
  items = rest.split('|')
  if items[0] == "1"
    result[date] = 1 
  else
    result[date] = ['', items[1..-1]]
  end
end
Sign up to request clarification or add additional context in comments.

2 Comments

This looks good so far. I'll give it a go tonight. I'll need to tweak it to create appropriate records in my DB but I can see the general idea. Thanks. Could you explain further about what this line is doing? result[date] = ['', items[1..-1]]
Much appreciate this. I modified it to create the required records in my database that I needed and then extended it further with more required functionality. Thanks for giving me a great starting point and to get me going on resolving this!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.