Sorting an array of hash in Ruby
2014-06-23 12:15
423 查看
I have one array of hashes as following:
I want to sort this array of hashes based on the value of key
I want sorted array like this:
ar = [{"k1"=>"v1", "k2"=>"75.1%"}, {"k1"=>"v2", "k2"=>"-NA-"}, {"k1"=>"v3", "k2"=>"5.1%"}] ar.sort_by{|h|(k2 = h["k2"]) == "-NA-"? -Float::INFINITY : -k2.to_f} #=>[{"k1"=>"v2", "k2"=>"-NA-"}, {"k1"=>"v1", "k2"=>"75.1%"}, {"k1"=>"v3", "k2"=>"5.1%"}]
a = [ {"k1"=>"v1", "k2"=>"75.1%"}, {"k1"=>"v2", "k2"=>"-NA-"}, {"k1"=>"v3", "k2"=>"5.1%"} ]
I want to sort this array of hashes based on the value of key
"k2". I want to sort it in the decreasing order with
"-NA-"coming at top always.
I want sorted array like this:
[{"k1"=>"v2", "k2"=>"-NA-"}, {"k1"=>"v1", "k2"=>"75.1%"}, {"k1"=>"v3", "k2"=>"5.1%"}]
na, rest = a.partition{|h| h["k2"] == "-NA-"} na + rest.sort_by{|h| h["k2"].to_f}.reverse[{"k1"=>"v1", "k2"=>"75.1%"}, {"k1"=>"v2", "k2"=>"-NA-"}, {"k1"=>"v3", "k2"=>"5.1%"}]
相关文章推荐
- Ruby: Sorting an array of strings, in alphabetical order, that includes some arrays of strings
- Matching Portions of A String to Elements of an Array in Ruby
- Finding sum of every combination of two numbers in an array in Ruby
- How to find number of a specific integer in an array of Fixnums ruby
- Get indices for sorted permutation of an array in Ruby?
- Condensing an array of hashes within that same array in Ruby
- Partially sorting an array in Ruby
- how to merge array of hash based same keys in ruby?
- Converting a array to an array of ranges in ruby
- How do I sort an array of hashes by a value in the hash?
- Distinguish between index of a decimal number and integer inside an array in Ruby?
- How do I sort an array of hashes by a value in the hash?
- Get nth element of an array in Ruby?
- Whats the best way to split an array in ruby into multiple smaller arrays of random size
- Convert Array to Hash while preserving Array index values in Ruby
- Ruby: Count unique elements and their occurences in an array
- CareerCup Eliminate all ‘b’ and ‘ac’ in an array of characters
- Wobble Hypothesis - Combination or Permutation of Array of strings in ruby
- Joining an array of keys to a hash with key value pairs like excel vlookup
- Filter (seach and replace) array of bytes in an InputStream