Skip to content

Instantly share code, notes, and snippets.

@Frost
Last active November 22, 2016 15:35
Show Gist options
  • Save Frost/7015012d9fcc2cd06d15a3aa5dfa4dee to your computer and use it in GitHub Desktop.
Save Frost/7015012d9fcc2cd06d15a3aa5dfa4dee to your computer and use it in GitHub Desktop.
Fun with ruby's Hash default
class Thing < ActiveRecord::Base
enum group: {
group_1: 0,
group_2: 1,
group_3: 2,
group_4: 3,
group_5: 4,
...
}
end
grouping = Hash.new([])
Thing.all.each_with_object(
grouping.merge({ "group_1" => [], "group_2" => [], "unassigned" => grouping.default })
) { |thing, hash|
hash[thing.group] << thing
}
# grouping will now have three keys, and any instances of Thing that has `.group` that isn't either `group_1` or `group_2` will end up in `grouping["unassigned"]`
@Frost
Copy link
Author

Frost commented Nov 22, 2016

More fun

> a = {}
> a.default = a
> a[:foo]
{}
> a[:foo][:bar] = "bar"
"bar"
> a
{:bar => "bar}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment