简体   繁体   中英

Convert comma-separated string into hash in 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.

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM