Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ProGM/297324a36bb4891196837277c01cc280 to your computer and use it in GitHub Desktop.
Save ProGM/297324a36bb4891196837277c01cc280 to your computer and use it in GitHub Desktop.
Ruby hash to dotted path

Convert a ruby hash to dotted path

def hash_to_dotted_path(hash, path = "")
  hash.each_with_object({}) do |(k, v), ret|
    key = path + k.to_s

    if v.is_a? Hash
      ret.merge! hash_to_dotted_path(v, key.to_s + ".")
    else
      ret[key] = v
    end
  end
end

# { :level1 => { :level2 => { :level3 => 123 } } }
# to
# { "level1.level2.level3" => 123 }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment