Skip to content

Instantly share code, notes, and snippets.

@guillermo
Created October 10, 2010 15:26
Show Gist options
  • Save guillermo/619321 to your computer and use it in GitHub Desktop.
Save guillermo/619321 to your computer and use it in GitHub Desktop.
hash to array with order
class HashToArrayWithOrder
class MaxDepth < Exception ; end
def self.new(data,max_level = 5)
raise MaxDepth if max_level==0
if data.is_a? Hash
data = data.sort{|a,b| a.class == b.class ? a.to_s <=> b.to_s : a.class.to_s <=> b.class.to_s}
end
return data unless data.is_a? Array
data.map {|array_element| new(array_element,max_level -1) }
end
end
describe HashToArrayWithOrder do
it "should get the same hash regarding the order of the keys for a hash" do
hash1 = {:a => {:small => 'asdf', :big => '100x300'}, :min => 3}
hash2 = {:min => 3, :a => {:big => '100x300', :small => 'asdf'}}
HashToArrayWithOrder.new(hash1).to_s == HashToArrayWithOrder.new(hash2).to_s
end
it "should raise an error if it reach max_level depth" do
hash = {:a => {:small => 'asdf', :big => '100x300'}, :min => 3}
lambda{ HashToArrayWithOrder.new(hash, 0) }.should raise_error(HashToArrayWithOrder::MaxDepth)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment