Skip to content

Instantly share code, notes, and snippets.

@mkuhnt
Last active October 6, 2021 12:48
Show Gist options
  • Save mkuhnt/6815250 to your computer and use it in GitHub Desktop.
Save mkuhnt/6815250 to your computer and use it in GitHub Desktop.

Revisions

  1. mkuhnt renamed this gist Oct 4, 2013. 1 changed file with 2 additions and 2 deletions.
    4 changes: 2 additions & 2 deletions gistfile1.rb → stringify_keys.rb
    Original file line number Diff line number Diff line change
    @@ -9,8 +9,8 @@ def transform_hash(original, options={}, &block)
    value
    end
    end
    block.call(result,key,value)
    result
    block.call(result,key,value)
    result
    }
    end

  2. mkuhnt created this gist Oct 3, 2013.
    35 changes: 35 additions & 0 deletions gistfile1.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,35 @@
    def transform_hash(original, options={}, &block)
    original.inject({}){|result, (key,value)|
    value = if (options[:deep] && Hash === value)
    transform_hash(value, options, &block)
    else
    if Array === value
    value.map{|v| transform_hash(v, options, &block)}
    else
    value
    end
    end
    block.call(result,key,value)
    result
    }
    end

    # Convert keys to strings
    def stringify_keys(hash)
    transform_hash(hash) {|hash, key, value|
    hash[key.to_s] = value
    }
    end

    # Convert keys to strings, recursively
    def deep_stringify_keys(hash)
    transform_hash(hash, :deep => true) {|hash, key, value|
    hash[key.to_s] = value
    }
    end


    h1 = {a: {b: "c", d: [{a: "test", b: "test 2"},{a: "test 3"}]}}
    puts h1
    puts stringify_keys(h1)
    puts deep_stringify_keys(h1)