How do I sort an array of hashes by a value in the hash?

后端 未结 4 1193
旧巷少年郎
旧巷少年郎 2020-12-07 11:05

This Ruby code is not behaving as I would expect:

# create an array of hashes
sort_me = []
sort_me.push({\"value\"=>1, \"name\"=>\"a\"})
sort_me.push({         


        
相关标签:
4条回答
  • 2020-12-07 11:29

    As per @shteef but implemented with the sort! variant as suggested:

    sort_me.sort! { |x, y| x["value"] <=> y["value"] }
    
    0 讨论(0)
  • 2020-12-07 11:31

    Although Ruby doesn't have a sort_by in-place variant, you can do:

    sort_me = sort_me.sort_by { |k| k["value"] }
    

    Array.sort_by! was added in 1.9.2

    0 讨论(0)
  • 2020-12-07 11:38

    You can use sort_me.sort_by!{ |k| k["value"]}. This should work.

    0 讨论(0)
  • 2020-12-07 11:46

    Ruby's sort doesn't sort in-place. (Do you have a Python background, perhaps?)

    Ruby has sort! for in-place sorting, but there's no in-place variant for sort_by in Ruby 1.8. In practice, you can do:

    sorted = sort_me.sort_by { |k| k["value"] }
    puts sorted
    

    As of Ruby 1.9+, .sort_by! is available for in-place sorting:

    sort_me.sort_by! { |k| k["value"]}
    
    0 讨论(0)
提交回复
热议问题