1

我有一些方法应该用地图方法代替。这对我来说是个问题)你们能帮帮我吗,伙计们?

这是我的方法:

def groupe_company_files(source_files)
      files = {}
      source_files.each do |file|
        category_name = file.company_files_category.present? file.company_files_category.name : I18n.t('company_files_categories.uncategorized')

        files[category_name] ||= []
        files[category_name] << file
      end
      files
end
4

1 回答 1

1

使用map

def groupe_company_files(source_files)
      files = Hash.new{[]}
      source_files.map{|f| files[f.company_files_category.try(:name) || I18n.t('company_files_categories.uncategorized')] += [f]}
      files  
end

使用inject

def groupe_company_files(source_files)
      source_files.inject(Hash.new{[]}){|h,f| h[f.company_files_category.try(:name) || I18n.t('company_files_categories.uncategorized')] += [f];h}
end

使用group_by

def groupe_company_files(source_files)
      source_files.group_by{|f| f.company_files_category.try(:name) || I18n.t('company_files_categories.uncategorized')}
end
于 2013-11-14T09:53:03.100 回答