1

How can I sort this array so all hashes with optional = true are last?

my_array = [
  { name: "foo", optional: true }, 
  { name: "pop" }, 
  { name: "boop", optional: true },
  { name: "pop", optional: false }
]

I tried this:

my_array.sort { |a,b| a['optional'] <=> b['optional'] }

But I get this error:

comparison of Hash with Hash failed

Error is surprising since doing a['optional'] would return a value of true, false, or nil.

Note:
I am aware of this solution .sort_by { |a| (a['optional'] ? 1 : 0) }. I would like to understand the sort method in particular.

2 Answers 2

6

Booleans are not ordinal data types - true is not larger or smaller than false, it's just not equal, so you can't use the <=> operator either. If you want to sort the array according to the optional property, you'd need some simple custom logic. E.g.:

my_array.sort { |a,b| a['optional'] == b['optional'] ? 0 : a['optional'] ? 1 : -1}
Sign up to request clarification or add additional context in comments.

Comments

1

For sort to work, you have to implement the block according to the documentation:

The block must implement a comparison between a and b, and return -1, when a follows b, 0 when a and b are equivalent, or +1 if b follows a.

@Mureinik already showed you how to do that.

Personally I'd recommend using sort_by, since that's basically exactly the use case it was made for.

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.