Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse a string representation of a hash

Tags:

ruby

hash

I have this string and I'm wondering how to convert it to a Hash.

"{:account_id=>4444, :deposit_id=>3333}"
like image 772
zoras Avatar asked Dec 23 '11 08:12

zoras


People also ask

Can a hash key Be a string?

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.

How do you turn a string into a hash?

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.

How do you convert to hash in Ruby?

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.

What is To_hash in Ruby?

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.


2 Answers

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.

like image 141
Jan Avatar answered Oct 16 '22 06:10

Jan


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.

like image 38
knut Avatar answered Oct 16 '22 05:10

knut