"10",153=>"85.0"}> 所以,我需要按第二个值按降序对哈希进行排序。我试过这个: var.-6ren">
gpt4 book ai didi

ruby-on-rails - rails : How to sort/re-order an OrderedHash

转载 作者:行者123 更新时间:2023-12-04 05:59:26 26 4
gpt4 key购买 nike

我有一个 OrderedHash,从答案 here 生成看起来像这样:

<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?

最佳答案

好吧,我想你可以简单地使用 :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]

关于ruby-on-rails - rails : How to sort/re-order an OrderedHash,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4317550/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com