是否有更有效的方法从Ruby对象集合构建排序哈希?

时间:2017-08-02 20:35:29

标签: ruby sorting hash

我正在构建一个已排序的哈希,以便在rails app中的分组选择中使用。我没有使用ActiveRecord。有没有比这更有效或更清洁的方式?

def for_select
  select_list = {}
  Department.all.each do |dept|
    select_list[dept.top_level_department_cn] ||= []
    select_list[dept.top_level_department_cn] << [dept.cn, dept.sorid]
  end
  select_list.each_value { |select_options| select_options.sort_by!(&:first) }
             .sort
             .to_h
end

2 个答案:

答案 0 :(得分:1)

def for_select
  Department.all
  .sort
  .group_by(&:top_level_department_cn)
  .each_value{|v| v.map!{|dept| [dept.cn, dept.sorid]}.sort_by!(&:first)}
end

答案 1 :(得分:1)

另一种解决方案:

def for_select
  # @see: https://stackoverflow.com/questions/2698460#answer-28916684
  select_list = Hash.new { |h, k| h[k] = [] }

  Department.all
    .map { |d| [d.top_level_department_cn, [d.cn, d.sorid]] }
    .sort
    .each { |top_level_cn, data| select_list[top_level_cn] << data }

  select_list
end