0

I'm working on a configuration file parser and I need help parsing key: value pairs into a hash.

I have data in the form of: key: value key2: value2 another_key: another_value.

So far I have code in form of

    line = line.strip!.split(':\s+')

which returns an array in the form of

["key:value"]["key2: value2"]["another_key: another_value"]

How can I turn these arrays into a single hash in the form of

{key=>value, key2=>value2, another_key=>another_value}

I'm not sure if the key:value pairs need to be in the form of a string or not. Whatever is easiest to work with.

Thanks for your help!


This is the solution I found:

    line = line.strip.split(':')
    hash = Hash[*line]

which results in the output{"key"=>"value"}, {"key2"=>"value2"}

2
  • Have a look at String#partition. That would be ideal for splitting each string into key and value, or use a regex with a capture group on each side of the colon. Commented Nov 15, 2013 at 2:20
  • Ah nice, String#partition is a useful method! Thanks @CarySwoveland Commented Nov 15, 2013 at 2:32

3 Answers 3

1

Very very close to Cary's solution:

Hash[*line.delete(':').split]
Sign up to request clarification or add additional context in comments.

2 Comments

That's why I still felt it was worth adding.
Ah, the price of honesty. :-)
1

Even simpler:

Hash[*line.gsub(':',' ').split]
  # => {"key"=>"value", "key2"=>"value2", "another_key"=>"another_value"} 

1 Comment

Good solution, I used this to come up with something of my own
1

Assuming the key and value are single words, I'd probably do something like this:

Hash[line.scan(/(\w+):\s?(\w+)/)]

You can change the regex if it's not quite what you are looking for.

1 Comment

Thanks @Nigel this works, but I'd rather not deal with the RegEx

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.