0

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?

4
  • 1
    What do you mean with not working properly? ["Box", "Pack", "ball", "ball -1", "new size", "new size 1", "wels"].sort == ["Box", "Pack", "ball", "ball -1", "new size", "new size 1", "wels"] # true Commented Apr 7, 2019 at 2:48
  • I mean after sorting by itemsize it's not coming properly. To show itemsize alone I am using select to filter the sorted key alone. Commented Apr 7, 2019 at 17:54
  • If u check the result the order should come in [ball, ball -1, Box , new size 1, pack wells], Commented Apr 7, 2019 at 17:56
  • But I didn't get expected results, Did u got my point? Commented Apr 7, 2019 at 17:56

3 Answers 3

1
@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.

Sign up to request clarification or add additional context in comments.

Comments

0

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 }

1 Comment

Thanks arieljuod for brief explanation.
0

You can try in following way:

sorted_arr = @final_array.collect{|arr| arr[:ItemSize]}.sort { | a1, a2 | a1.downcase <=> a2.downcase }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.