2012-06-05 26 views
1

我想通過對象last_name對對象數組排序,但總是將某個對象放在數組的第一個位置。 爲了實現這一點,我已經嘗試了很多,但總是失敗的數組結果。這裏是我的嘗試之一,因爲我不能運行的結果數組對象(例如@team.each do |m| puts m.username end失敗)的任何方法,其中失敗:Ruby:排除一個異常的數組

if @team = UserGroup.find_by_name("team").users.sort_by(&:last_name) 
    if first_member = @team.detect{|m| m.username == "test"} 
    @team.unshift @team.reject{|m| m.username == "test"} 
    end 
end 

感謝您的幫助。

回答

3

您可以使用SQL的ORDER BY能力,速度比紅寶石(順便說一句,你應該使用find_by_attribute!)。未經檢驗的,但像這樣玩:

@team = UserGroup.find_by_name!("team").users. 
    order("username = 'test' DESC, last_name ASC") 

當然你也可以使用紅寶石一樣的想法:

@team = UserGroup.find_by_name!("team").users. 
    sort_by { |u| [u.username == 'test' ? 0 : 1, u.last_name] } 
+0

我必須同意,你的解決方案更好,更快。謝謝! :) – alexschomb

1

試試這個:

@team = UserGroup.find_by_name("team").users.sort_by(&:last_name) 
first_member = @team.select{|m| m.username == "test"} 
@team = first_member + (@team - first_member) 
+0

哇,謝謝。解決方案可以很簡單。 :)它甚至可以在沒有用戶「測試」的情況下工作,太棒了! – alexschomb

+0

沒關係,因爲它解決了OP的意圖,但注意你可以在'sort_by'中包含'm.username =='test'',它會更短更快。 – tokland

1

如果我理解你的權利,這應該工作:

@team = UserGroup.find_by_name("team").users.sort_by(&:last_name) 
test=nil 
@[email protected]_if {|obj| obj.username == "test" ? (test=obj; true) : false} 
@team.insert(0, test) 
+0

感謝您的回答。這可能也會起作用,但我會使用Matzi的解決方案來簡化操作。 – alexschomb

1

回答這個問題的標題:「有一個例外排序的數組」:

這裏的例外是13,所以它總是獲得最高排名:在IRB

(1..15).to_a.shuffle.sort { |a,b| a == 13 ? -1 : b == 13 ? 1 : a <=> b } 

輸出:

=> [13, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 15] 

也與用戶名,如果需要的工作:

%w{mike bob mario toad test}.sort {|a,b| a == 'test' ? -1 : b == 'test' ? 1 : a <=> b } 
=> ["test", "bob", "mario", "mike", "toad"]