【发布时间】:2011-06-13 18:47:06
【问题描述】:
好的,我有一个由 4 个对象组成的数组,例如
=> [#<Graphic id: 3...">, #<Collection id: 1....">, #<Category id:...">, #<Volume id: 15...">]
matches.size
=> 4
有 4 个不同的对象(图形、集合、类别、体积)我现在需要根据对象将它们分成 4 个数组。所以我创建了这个方法,它可以工作,但它太老套了......关于如何以更简洁的方式实现同样事情的任何想法......更多 rubyesk
这是我的方法
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, sub_categories.flatten]
end
【问题讨论】:
-
请注意,“case group.first”和“when Graphic”应该足够了,case 更广泛 ===,而不是 ==
标签: ruby-on-rails ruby arrays ruby-on-rails-3 group-by