More concise way of doing the grouping in Ruby
Ok so i have an array of 4 objects like
=> [#<Graphic id: 3...">, #<Collection id: 1....">, #<Category id:...">, #<Volume id: 15...">]
matches.size
=> 4
with 4 different objects (Graphic, Collection, Category, Volume) I now need to separate these into 4 arrays based on the objects. So i created this method and it works but its so hackish....any ideas on how to achieve the same thing in a more concise way ...more rubyesk
Here is my method
def self.get_results(matches)
graphics = [], collections = [], categories = [], sub_categories = []
matches.group_by(&:class).each do |key, group|
case group.first.class.to_s
when "Graphic"
graphics << group
when "Category"
categories << group
when "SubCategory"
sub_categories << group
when "Collection"
collections << group
end
end
[graphics.flatten, collections.flatten, categories.flatten,开发者_StackOverflow社区 sub_categories.flatten]
end
matches_by = matches.group_by {|m| m.class.to_s }
%w{Graphic Category SubCategory Collection}.map do |class_name|
matches_by[class_name] || []
end
If you don't care what order they're in, try this
matches.group_by {|m| m.class.to_s }.values
If you just want a Hash, indexed by the class name (where the value of each entry is an Array of objects of that type), it's simply
matches.group_by {|m| m.class.to_s }
ret = {}
matches.group_by(&:class).each do |klass, item|
ret[klass.to_s] = item
end
ret.values
精彩评论