Skip to content

Instantly share code, notes, and snippets.

@whilp
Created November 18, 2010 20:38
Show Gist options
  • Save whilp/705571 to your computer and use it in GitHub Desktop.
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
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"}]
@whilp
Copy link
Author

whilp commented Nov 18, 2010

The following Python does what I want; I still don't see why the Ruby doesn't...

before = {
    "key1": {"type": "a"},
    "key2": {"type": "a"},
    "key3": {"type": "b"},
}

after = {}
for k, v in before.items():
    after.setdefault(v["type"], []).append(v)

for k, v in after.items():
    print ">>> %s %s" % (k, v)

@whilp
Copy link
Author

whilp commented Nov 18, 2010

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