How to Convert a String Object into a Hash Object

How do I convert a String object into a Hash object?

The string created by calling Hash#inspect can be turned back into a hash by calling eval on it. However, this requires the same to be true of all of the objects in the hash.

If I start with the hash {:a => Object.new}, then its string representation is "{:a=>#<Object:0x7f66b65cf4d0>}", and I can't use eval to turn it back into a hash because #<Object:0x7f66b65cf4d0> isn't valid Ruby syntax.

However, if all that's in the hash is strings, symbols, numbers, and arrays, it should work, because those have string representations that are valid Ruby syntax.

How to turn into a hash what has been made into a string of a hash?

str = "{ H: 50, Q: 25, D: 10, N: 5, P: 1 }"

str.gsub(/(\S+): +(\d+)/).with_object({}) { |_,h| h[$1.to_sym] = $2.to_i }
#=> {:H=>50, :Q=>25, :D=>10, :N=>5, :P=>1}

This employs the form of String#gsub that takes an argument and no block, returning an enumerator that can be chained to Enumerator#with_object. This form of gsub merely generates matches; it makes no substitutions.

One advantage of this construct is that it avoids the creation of temporary arrays.

The regular expression can be written in free-spacing mode to make it self-documenting.

/
(\S+) # match 1+ characters other than whitespaces, save to capture group 1
:[ ]+ # match ':' followed by 1+ spaces
(\d+) # match 1+ digits, save to capture group 2
/x # free-spacing regex definition mode

Ruby Convert String to Hash

You can use eval(@data), but really it would be better to use a safer and simpler data format like JSON.

How can I parse these hashes turned string, from my Ruby on Rails API so that it's accessible as an object in Javascript?

Following radiantshaw's lead, using either

eval("{\"x\"=>15, \"y\"=>7}")

or

JSON.parse("{\"x\"=>15, \"y\"=>7}".gsub('=>', ':'))

I got the following: {"x"=>15, "y"=>7}, which is a Ruby object. However in order to convert this to a Javascript object, I also needed to convert it to json.

So by taking it one step further, I am able to parse it into json like so:

Put require 'json' in the .rb file, and then do {"x"=>15, "y"=>7}.to_json which will result in

"{\"x\":15,\"y\":7}".

How to convert a string to a hash in Ruby on Rails without using eval?

As mentioned earlier, you should use eval. Your point about eval executing return_misc_definitions doesn't make sense. It will be executed either way.

h1 = {:status => {:label => 'Status', :collection => return_misc_definitions('project_status') } }
# or
h2 = eval("{:status => {:label => 'Status', :collection => return_misc_definitions('project_status') } }")

There's no functional difference between these two lines, they produce exactly the same result.

h1 == h2 # => true

Of course, if you can, don't use string represenstation of ruby hashes. Use JSON or YAML. They're much safer (don't require eval).

how to convert anything to a string / bytes object so it can be hashed

This is working for now, not optimal or efficient, but its fine for what I need.

def string_this(thing):
'''
https://stackoverflow.com/questions/60103855/how-to-convert-anything-to-a-
string-bytes-object-so-it-can-be-hashed
attempts to turn anything into a string that represents its underlying data
most accurately such that it can be hashed.
'''
if isinstance(thing, str):
return thing
try:
# objects like DataFrames
return thing.to_json()
except Exception:
try:
# other things without built in to_json serializable functions
return json.dump(thing)
except Exception:
# hopefully its a python primative type
return str(thing)


Related Topics



Leave a reply



Submit