Created
November 18, 2010 20:38
-
-
Save whilp/705571 to your computer and use it in GitHub Desktop.
I'd expect the following to produce output like this: >>> a [{:type=>"a"}, {:type=>"a"}] >>> b [{:type=>"b"}] Instead, I get: >>> a [{:type=>"b"}, {:type=>"a"}, {:type=>"a"}] >>> b [{:type=>"b"}, {:type=>"a"}, {:type=>"a"}] W
This file contains 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
before = { | |
"key1" => {:type => "a"}, | |
"key2" => {:type => "a"}, | |
"key3" => {:type => "b"}, | |
} | |
after = Hash.new([]) | |
before.each{|k,v| after[v[:type]] <<= v} | |
after.each{|k,v| puts ">>> #{k} #{v.inspect}"} | |
# I expect output like the following: | |
# >>> a [{:type=>"a"}, {:type=>"a"}] | |
# >>> b [{:type=>"b"}] | |
# That is, all values in each key of 'after' should have :type matching the key. | |
# Instead, I get: | |
# >>> a [{:type=>"b"}, {:type=>"a"}, {:type=>"a"}] | |
# >>> b [{:type=>"b"}, {:type=>"a"}, {:type=>"a"}] |
Sigh. This version of the Ruby works. It's more explicit (and less sugary), but I still don't see why my first crack at it fails.
before = {
"key1" => {:type => "a"},
"key2" => {:type => "a"},
"key3" => {:type => "b"},
}
after = {}
for k, v in before
type = v[:type]
after[type] || after[type] = []
after[type] << v
end
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The following Python does what I want; I still don't see why the Ruby doesn't...