Skip to content

Instantly share code, notes, and snippets.

@matthewrudy
Created August 4, 2011 23:35
Show Gist options
  • Save matthewrudy/1126580 to your computer and use it in GitHub Desktop.
Save matthewrudy/1126580 to your computer and use it in GitHub Desktop.
myhash = {
{"var1"=>"a", "var2"=>"a"} => 1,
{"var1"=>"a", "var2"=>"b"} => 2,
{"var1"=>"b", "var2"=>"a"} => 3,
{"var1"=>"b", "var2"=>"b"} => 4,
}
nested = {
"a"=> {
"a"=> 1,
"b"=> 2
},
"b"=> {
"a"=> 3,
"b"=> 4
}
}
def index(hash, fields)
# store the last index of the fields
last_field = fields.length - 1
# our indexed version
indexed = {}
hash.each do |key, value|
# our current point in the indexed hash
point = indexed
fields.each_with_index do |field, i|
key_field = key[field]
if i == last_field
point[key_field] = value
else
# ensure the next point is a hash
point[key_field] ||= {}
# move our point up
point = point[key_field]
end
end
end
# return our indexed hash
indexed
end
raise "doesnt work" unless index(myhash, ["var1", "var2"]) == nested
puts "looks like it works"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment