Reputation: 758
I have to know, if I'll make string from struct (using .to_s) is there any way to make it struct back ? I wonder if there is some helper class or something.
My case of use is to hold or info in struct, then send it through the internet and build a struct from it on the other side.
Thanks in advance.
Upvotes: 3
Views: 1172
Reputation: 35788
To flush out the other options given by @Semyon above:
YAML
Portable, but rather Ruby specific in its use. Supports serializing any Ruby object in a special way that only Ruby can really understand. If you want portability between Rubies but not languages, YAML is the way to go:
require 'yaml'
obj = [1,2,3]
YAML.dump(obj) #=> Something like "---\n- 1\n- 2\n- 3\n"
YAML.load(YAML.dump(o)) #=> [1,2,3]
JSON
JSON is the most widely recognized and portable data standard for these kinds of things. Portable between Rubies, languages, and systems.
require 'json'
obj = [1,2,3]
obj.to_json #=> "[1,2,3]"
JSON.load("[1,2,3]") #=> [1,2,3]
Both, unlike Marshal
, are human readable.
Upvotes: 3
Reputation: 20649
String that you get from struct.to_s
is made for inspection only. To transfer your struct you will need to serialize it on the one side and deserialize it from the other side. There are a variety of formats including JSON, YAML and Marshal. The last one produces non human-readable byte streams but it is the most easy to use:
Person = Struct.new(:first_name, :last_name)
me = Person.new("Semyon", "Perepelitsa")
p data = Marshal.dump(me)
"\x04\bS:\vPerson\a:\x0Ffirst_nameI\"\vSemyon\x06:\x06ET:\x0Elast_nameI\"\x10Perepelitsa\x06;\aT"
# on the other side
p Marshal.load(data)
#<struct Person first_name="Semyon", last_name="Perepelitsa">
Upvotes: 2