Reputation:
I have a data structure consisting of nested built-in Ruby types, such as hashes, arrays, keywords, numbers and strings. I would like to transform that to a literal form, such that evaluating that form yields the given data structure.
For instance:
[ { :some => [ 'thing' ] }, 42 ] -> "[ { :some => [ 'thing' ] }, 42 ]"
This could be obtained by recursively visiting the structure and handling all the desired built-in types, but I am wondering if there is some suitable built-in/library solution I could use instead.
Clarification: The output is going to be used in the context of code generating Ruby code so alternatives such as JSON is not what I'm after.
Upvotes: 3
Views: 238
Reputation: 6409
Object#inspect is probably what you're looking for. It will produce ruby representations for all the types you listed. Though that might start to fall apart for more complex types like dates, etc.
1.9.3 (main):0 > puts [ { :class => [ 'thing' ] }, 42 ].inspect
[{:class=>["thing"]}, 42]
Upvotes: 2
Reputation: 3785
You can use Marshal. It's ruby-core library.
http://www.ruby-doc.org/core-1.9.3/Marshal.html
From readme:
The marshaling library converts collections of Ruby objects into a byte stream, allowing them to be stored outside the currently active script. This data may subsequently be read and the original objects reconstituted.
Upvotes: 2
Reputation: 5626
There are a few options, JSON and YAML are probably the two most popular in Ruby.
# using JSON
serialized = JSON.dump([ { :some => [ 'thing' ] }, 42 ])
deserialized = JSON.load(serialized)
# using YAML
serialized = YAML.dump([ { :some => [ 'thing' ] }, 42 ])
deserialized = YAML.load(serialized)
Upvotes: 2