In Ruby, I need to convert a string like this:
"keyA,valueA,keyB,valueB"
into a hash like this:
{"keyA"=>"valueA", "keyB"=>"valueB"}
I'm pretty sure this will involve the each_slice method and possibly the enumerable inject(), as described in "ruby string to hash conversion".
but I have no idea how to bring these components together.
s = 'keyA,valueA,keyB,valueB'
Hash[*s.split(',')]
#=> { 'keyA' => 'valueA', 'keyB' => 'valueB' }
Try this:
s = "keyA,valueA,keyB,valueB"
Hash[*s.split(",").each_slice(2).collect{ |k,v| [k,v] }.flatten]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With