I have this string and I'm wondering how to convert it to a Hash.
"{:account_id=>4444, :deposit_id=>3333}"
The keys and value in hash tables are also . NET objects. They are most often strings or integers, but they can have any object type.
hashCode() method of String class can be used to convert a string into hash code. hashCode() method will return either negative or positive integer hash values.
The ActiveRecord#attributes is another method you can use. Given an active record, attributes returns a hash of all the attributes with their names as keys and the values of the attributes as values. The attributes method returns a hash where all the keys are strings.
Hash#to_hash() is a Hash class method which returns the self – hash representation of the hash. Syntax: Hash.to_hash() Parameter: Hash values. Return: self object.
The way suggested in miku's answer is indeed easiest and unsafest.
# DO NOT RUN IT
eval '{:surprise => "#{system \"rm -rf / \"}"}'
# SERIOUSLY, DON'T
Consider using a different string representation of your hashes, e.g. JSON or YAML. It's way more secure and at least equally robust.
With a little replacement, you may use YAML:
require 'yaml'
p YAML.load(
"{:account_id=>4444, :deposit_id=>3333}".gsub(/=>/, ': ')
)
But this works only for this specific, simple string. Depending on your real data you may get problems.
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