Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert String to Hash

Tags:

ruby

hash

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.

like image 550
Eugen Avatar asked Jun 13 '26 10:06

Eugen


2 Answers

Hash[*string.split(/[:\n]/)]
# => {"range"=>"12", "type"=>"default"} 
like image 141
Santhosh Avatar answered Jun 15 '26 01:06

Santhosh


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"}
like image 40
Patrick Oscity Avatar answered Jun 15 '26 02:06

Patrick Oscity



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!