2010-11-30 161 views
6

我有一個OrderedHash,從看起來像這樣的答案here產生:Rails的:如何排序/重新排序的OrderedHash

<OrderedHash {2=>"534.45",7=>"10",153=>"85.0"}> 

所以,我需要通過第二個值到哈希排序,在降序。我試過這個:

var.sort! {|a,b| b[1] <=> a[1]} 
NoMethodError: undefined method `sort!' for #<ActiveSupport::OrderedHash:0x127a50848> 

我該如何重新訂購OrderedHash?

+0

@Shtééf的答案對我來說很好,但我可以建議治療紅寶石紅寶石而不是其他的語言嗎?想要讓ruby看起來像php一樣,這很不幸。也許你可以解釋下一次你希望達到的目標。 – noodl 2010-11-30 19:37:11

回答

8

那麼,我認爲你可以簡單地使用:order => 'sum_deal_price ASC'sum調用原始答案。

但你也可以做到在Ruby中,它只是有點棘手:

# You can't sort a Hash directly, so turn it into an Array. 
arr = var.to_a # => [[2, "534.45"], [7, "10"], [153, "85.0"]] 
# Looks like there's a bunch of floats-as-strings in there, fix that. 
arr.map! { |pair| [pair.first, pair.second.to_f] } 
# Now sort it by the value (which is the second entry of the pair). 
arr.sort! { |a, b| a.second <=> b.second } 
# Turn it back into an OrderedHash. 
sorted_hash = ActiveSupport::OrderedHash[arr] 
+0

deal.price的訂單似乎不起作用。與結果集相比,我得到的結果遍佈整個地圖。使用你的第二個建議(除了排序!,我不得不使用{| a,b | b [1] <=> a [1]}),但我很關心時間。我正在查看80,000條記錄,並將它們來回轉換需要相當長的一段時間。 – 2010-11-30 19:40:43