Rails 中使用布尔值进行 sort_by
我知道 Ruby 中的布尔值是类。但从实际的角度来看,有没有一种方法可以按布尔值对数组进行排序(即,首先将所有具有真值的元素排序)?
谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
你可以作弊并让它返回一个数字:
You could cheat and get it to return a number:
您可以使用分区,然后展平结果:
You could use partition and then flatten the results:
通过使用 ActiveRecord 的顺序(包含在 Rails 中):
By using ActiveRecord's order (included in Rails):
由于这里有几种不同的表示方式,我继续对它们进行基准测试,看看哪一种最快,根据布尔属性对 27,000 个项目进行排序:
所以,是的,将事物保留在 SQL 端肯定会让事情变得更快。
Since there are a couple different ways represented here, I went ahead and benchmarked them to see which is fastest, sorting 27,000 items based upon a boolean attribute:
So yes, keeping things on the SQL side definitely makes things faster.