Reputation: 45
I have an array of hash, sorting by particular key not properly working,
The array of hash is:
@final_array = [{:Region=>"region - 1", :ItemSize=>"Box", :Price=>""}, {:Region=>"region - 1", :ItemSize=>"Pack", :Price=>""}, {:Region=>"region - 1", :ItemSize=>"ball", :Price=>""}, {:Region=>"region - 1", :ItemSize=>"ball -1", :Price=>""}, {:Region=>"region - 1", :ItemSize=>"new size", :Price=>""}, {:Region=>"region - 1", :ItemSize=>"new size 1", :Price=>""}, {:Region=>"region - 1", :ItemSize=>"wels", :Price=>""}]
@final_array = @final_array.sort_by { |x, y| x[:ItemSize] }
After sorting I am checking array by select query.
a = []
@final_array.select{ |x, y| a << x[:ItemSize] }
a
# => ["Box", "Pack", "ball", "ball -1", "new size", "new size 1", "wels"]
It's not properly working.
How do I solve this problem?
Upvotes: 0
Views: 382
Reputation: 154
You can try in following way:
sorted_arr = @final_array.collect{|arr| arr[:ItemSize]}.sort { | a1, a2 | a1.downcase <=> a2.downcase }
Upvotes: 0
Reputation: 6082
@final_array = @final_array.sort_by { |x, y| x[:ItemSize].downcase }
This makes sure that the case you pass into sort_by
is all the same. It does not change the case of the ItemSize values.
Upvotes: 1
Reputation: 15838
If you compare 2 strings for sorting with just str1 <=> str2
, upcase letters comes before downcase letter: A B C ... Y Z a b c ... y z. That's why you get Box
and Pack
before ball
.
Turn everything to the same case if you want' it case insensitive.
@final_array.sort_by { |x, y| x[:ItemSize].downcase }
Anyway, I personally don't like sorting hashed, I would better get the values I need as an array and then order that array.
ordered = @final_array.map{|x| x[:ItemSize] }.sort_by{|x| x.downcase }
Upvotes: 0