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)

  def noderize(key, value)
    if value.class == Hash
      node_value = serialize(value).join
      node_value = value.nil? ? "" : value


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:

    <street>R Jose Ananias Mauad</street>

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

  • 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.