2017-08-02 45 views
0

我正在構建一個分類的散列,用於在Rails應用程序中的分組選擇。我沒有使用ActiveRecord。有沒有比這更高效或更清潔的方法?有沒有一種更有效的方法來從Ruby對象集合中構建排序哈希?

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 
+1

什麼'Department.all'如果不是ActiveRecord的? –

+1

這是LDAP條目的自定義對象。 – HarlemSquirrel

回答

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 
+0

排序本身不起作用,因爲'Department'不是ActiveRecord模型。我沒有忘記'#group_by'枚舉器,這在這裏非常有幫助! – HarlemSquirrel

+0

另外,用'sort_by(&:cn)'排序最初的部門集合使得第二個'#sort_by!'不必要。 – HarlemSquirrel

+1

如果你在'Department'上定義'<=>',那麼'.sort'就可以工作。 :) –

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 
+0

我不知道我可以用默認值創建一個散列。這太酷了!但是,在鏈接的SO答案中,作者推薦'Hash.new([]。freeze)',我更喜歡這樣做。 – HarlemSquirrel

+0

這是正確的,但在這種情況下,您必須每次都實例化一個新數組:'.each {| top_level_cn,data | select_list [top_level_cn] + = [data]}',這在我看來不太直觀(你必須像這樣讀取:'.each {| top_level_cn,data | select_list [top_level_cn] = select_list [top_level_cn] + [數據]}') – romainsalles

相關問題