Created
July 28, 2010 15:16
-
-
Save igrigorik/494848 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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