Skip to content

Instantly share code, notes, and snippets.

@igrigorik
Created July 28, 2010 15:16
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 igrigorik/494848 to your computer and use it in GitHub Desktop.
Save igrigorik/494848 to your computer and use it in GitHub Desktop.
# silly but useful.
# -> compresses nested hashes into dot separated key value pairs
class Hash
def nested_flatten(prefix = 'h')
arr = []
each do |key, value|
k = prefix + ".#{key}"
if value.is_a? Hash
arr += value.nested_flatten(k)
elsif value.is_a? Array
arr += value.map {|v| [k, v]}
else
arr.push [k, value]
end
end
arr
end
end
if $0 == __FILE__
require 'rubygems'
require 'spec/autorun'
describe Hash do
it "should flatten simple hash" do
h = {1 => 2}.nested_flatten('pr')
h.size.should == 1
h.first[0].should == "pr.1"
h.first[1].should == 2
end
it "should accepted nested hashes" do
h = {1 => {2 => 3, 4 => 5}, 6 => 7}.nested_flatten('pr')
h.size.should == 3
h.flatten.include? "pr.1.2"
h.flatten.include? "pr.1.4"
h.flatten.include? "pr.6"
end
it "should accept nested arrays" do
h = {1 => [2,3,4]}.nested_flatten('pr')
h.size.should == 3
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment