3

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.

5
  • 1
    give us a sample input and expected output too. Commented Apr 4, 2013 at 12:14
  • 2
    You better use more standard medium, such as JSON. Write methods to convert your struct to/from JSON and you're good. Commented Apr 4, 2013 at 12:14
  • @iAmRubuuu whatever u can imagine ;) just needed example Commented Apr 4, 2013 at 12:15
  • @SergioTulentsev seems legit, i totally forgot about alternatives :) Thanks Commented Apr 4, 2013 at 12:16
  • @SergioTulentsev can you join here? chat.stackoverflow.com/rooms/27184/ruby-conceptual Commented Apr 4, 2013 at 13:05

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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">

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.