Given a string, such as "ABCD 100"
, what is the most efficient way to convert it into {"ABCD": 100}
, where "ABCD"
is the key and 100
is an integer and the value?
Assuming that you have more than one key-value pair, you can combine split
, each_slice
and map
:
"ABCD 100 EFG 200".split
.each_slice(2)
.map {|k, v| [k.to_sym, v.to_i]}.to_h
#=> {:ABCD=>100, :EFG=>200}
Or with scan
and groups:
"ABCD 100 EFG 200".scan(/([A-Z]+)\s([0-9]+)/)
.map! {|k, v| [k.to_sym, v.to_i]}.to_h
#=> {:ABCD=>100, :EFG=>200}
Use regex according to your actual issue, it is just an instance.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments