[英]Is there a more efficient way to build a sorted hash from a collection of Ruby objects?
我正在構建一個排序的哈希,以供在Rails應用程序中的分組選擇中使用。 我沒有使用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
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
另一個解決方案:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.