Rails 中使用布尔值进行 sort_by

发布于 2024-12-25 02:57:22 字数 85 浏览 2 评论 0原文

我知道 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

浸婚纱 2025-01-01 02:57:22

你可以作弊并让它返回一个数字:

sort_by { |a| a.thing ? 0 : 1 }

You could cheat and get it to return a number:

sort_by { |a| a.thing ? 0 : 1 }
智商已欠费 2025-01-01 02:57:22

您可以使用分区,然后展平结果:

partition{|v| v == true}.flatten

You could use partition and then flatten the results:

partition{|v| v == true}.flatten
骑趴 2025-01-01 02:57:22

通过使用 ActiveRecord 的顺序(包含在 Rails 中):

collection.order(thing: :desc)

By using ActiveRecord's order (included in Rails):

collection.order(thing: :desc)
你是我的挚爱i 2025-01-01 02:57:22

由于这里有几种不同的表示方式,我继续对它们进行基准测试,看看哪一种最快,根据布尔属性对 27,000 个项目进行排序:

Rehearsal ---------------------------------------------
sort_by     0.070000   0.000000   0.070000 (  0.075203)
partition   0.110000   0.000000   0.110000 (  0.114667)
order       0.000000   0.000000   0.000000 (  0.000046)
------------------------------------ total: 0.180000sec

            user     system      total        real
sort_by     0.010000   0.000000   0.010000 (  0.016611)
partition   0.110000   0.000000   0.110000 (  0.111384)
order       0.000000   0.000000   0.000000 (  0.000047)

所以,是的,将事物保留在 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:

Rehearsal ---------------------------------------------
sort_by     0.070000   0.000000   0.070000 (  0.075203)
partition   0.110000   0.000000   0.110000 (  0.114667)
order       0.000000   0.000000   0.000000 (  0.000046)
------------------------------------ total: 0.180000sec

            user     system      total        real
sort_by     0.010000   0.000000   0.010000 (  0.016611)
partition   0.110000   0.000000   0.110000 (  0.111384)
order       0.000000   0.000000   0.000000 (  0.000047)

So yes, keeping things on the SQL side definitely makes things faster.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文