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\$
  • 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 Jun 17 '18 at 13:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.