Skip to content

Instantly share code, notes, and snippets.

@fguillen
Created December 30, 2011 17:05
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fguillen/1540618 to your computer and use it in GitHub Desktop.
Save fguillen/1540618 to your computer and use it in GitHub Desktop.
to_hash recursive for HashWithIndifferentAccess
class HashWithIndifferentAccess < Hash
def to_hash_recursive
result = self.to_hash
result.each do |key, value|
if(value.is_a? HashWithIndifferentAccess)
result[key] = value.to_hash_recursive
end
end
result
end
end
@pacojp
Copy link

pacojp commented Nov 27, 2012

how about this?

class Hash
  def to_hash_recursive
    result = self.to_hash

    result.each do |key, value|
      case value
      when Hash
        result[key] = value.to_hash_recursive
      when Array
        result[key] = value.to_hash_recursive
      end
    end

    result
  end
end

class Array
  def to_hash_recursive
    result = self

    result.each_with_index do |value,i|
      case value
      when Hash
        result[i] = value.to_hash_recursive
      when Array
        result[i] = value.to_hash_recursive
      end
    end

    result
  end
end

@qichunren
Copy link

@pacojp works perfect!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment