Last active
November 22, 2016 15:35
-
-
Save Frost/7015012d9fcc2cd06d15a3aa5dfa4dee to your computer and use it in GitHub Desktop.
Fun with ruby's Hash default
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
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"]` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
More fun