Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert comma-separated string into hash in ruby

Tags:

ruby

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.

like image 498
Steve M Avatar asked Aug 06 '26 12:08

Steve M


2 Answers

s = 'keyA,valueA,keyB,valueB'

Hash[*s.split(',')]
#=> { 'keyA' => 'valueA', 'keyB' => 'valueB' }
like image 67
Jörg W Mittag Avatar answered Aug 09 '26 07:08

Jörg W Mittag


Try this:

s = "keyA,valueA,keyB,valueB"
Hash[*s.split(",").each_slice(2).collect{ |k,v| [k,v] }.flatten]
like image 32
Thilo Avatar answered Aug 09 '26 05:08

Thilo