2
\$\begingroup\$

I've just made this "serialization" module in Ruby that takes a hash and outputs a XML string.

module Xml extend self def serialize(hash_obj) hash_obj.map do |key, value| noderize(key, value) end end def noderize(key, value) if value.class == Hash node_value = serialize(value).join else node_value = value.nil? ? "" : value end "<#{key}>#{node_value}</#{key}>" end end puts Xml.serialize({ name: "Vinicius", username: "vnbrs", address: { country: { name: "Brazil", dial_code: 55 }, street: "R Jose Ananias Mauad", street_number: nil, } }) 

And that outputs:

<name>Vinicius</name> <username>vnbrs</username> <address> <country> <name>Brazil</name> <dial_code>55</dial_code> </country> <street>R Jose Ananias Mauad</street> <street_number></street_number> </address> 

I've used #map and some recursion. How could that be improved? Is it a bad implementation?

\$\endgroup\$
1
  • 2
    \$\begingroup\$This looks good to me. To don't see redundant or unnecessary operations. Recursion is a good fit when you don't know how deeply nested something can be, so I don't foresee any problems there either. Good job\$\endgroup\$
    – Zack
    CommentedJun 17, 2018 at 13:22

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.