Im wondering if there is a better way of converting a string to a Hash. My String will always look exactly the same regarding the structure. Here is an example:
string = "range:12\ntype:default\n"
@settings = Hash[
*string.downcase
.split("\n")
.map{|s| [s.split(":")[0].to_sym, s.split(":")[1]]}
.flatten
]
p @settings
# => {:range=>"12", :type=>"default"}
This does what it should do and I have no problems with this. But it is extremely unreadable and I hope that there are some refactoring options for my code.
Hash[*string.split(/[:\n]/)]
# => {"range"=>"12", "type"=>"default"}
You can use String.scan to search for key-value pairs in the string and then convert the resulting array of arrays to a hash by simply calling to_h:
string.scan(/(.+):(.+)\n/).to_h
#=> {"range"=>"12", "type"=>"default"}
If you really need the symbol keys, you can use Array#map before converting to a hash:
string.scan(/(.+):(.+)\n/).map {|k,v| [k.to_sym, v]}.to_h
#=> {:range=>"12", :type=>"default"}
If you're using Rails, there's already the built in method Hash#symbolize_keys:
string.scan(/(.+):(.+)\n/).to_h.symbolize_keys
#=> {:range=>"12", :type=>"default"}
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