I know that boolean in Ruby are classes. But from practical point of view, is there a way to sort an array by boolean (i.e., with all elements with true value first)?
Thank you.
In Ruby, a boolean refers to a value of either true or false , both of which are defined as their very own data types. Every appearance, or instance, of true in a Ruby program is an instance of TrueClass , while every appearance of false is an instance of FalseClass .
true , false , and nil are special built-in data types in Ruby. Each of these keywords evaluates to an object that is the sole instance of its respective class. true and false are Ruby's native boolean values. A boolean value is a value that can only be one of two possible values: true or not true.
You could cheat and get it to return a number:
sort_by { |a| a.thing ? 0 : 1 }
You could use partition and then flatten the results:
partition{|v| v == true}.flatten
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With