Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sort_by with Boolean in Rails

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.

like image 308
AdamNYC Avatar asked Jan 05 '12 03:01

AdamNYC


People also ask

How do you define a boolean in Ruby?

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 .

What are the boolean values in Ruby?

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.


2 Answers

You could cheat and get it to return a number:

sort_by { |a| a.thing ? 0 : 1 }
like image 97
Ryan Bigg Avatar answered Oct 09 '22 23:10

Ryan Bigg


You could use partition and then flatten the results:

partition{|v| v == true}.flatten
like image 21
josephrider Avatar answered Oct 10 '22 00:10

josephrider