如何在 Ruby 中创建自定义排序方法

编程入门 行业动态 更新时间:2024-10-21 12:01:02
本文介绍了如何在 Ruby 中创建自定义排序方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想指定一个自定义块方法,通过评估两个属性来对对象数组进行排序.但是,经过多次搜索,我没有找到任何没有 <=> 运算符的示例.

I want to specify a custom block method to sort an object array by evaluating two properties. However, after many searches, I didn't find to any example without the <=> operator.

我想将 a 与 b 进行比较:

I want to compare a to b:

if a.x less than b.x return -1 if a.x greater than b.x return 1 if a.x equals b.x, then compare by another property , like a.y vs b.y

这是我的代码,但它不起作用:

This is my code and it doesn't work:

ar.sort! do |a,b| if a.x < b.y return -1 elseif a.x > b.x return 1 else return a.y <=> b.y end

这个块在一个函数内 return 正在退出函数并返回 -1.

This block is within a function return is exiting the function and returning -1.

推荐答案

最佳答案由@AJcodez提供如下:

The best answer is provided by @AJcodez below:

points.sort_by{ |p| [p.x, p.y] }

我最初提供的正确"答案虽然在技术上有效,但不是我建议编写的代码.我记得我的回答是为了适应问题对 if/else 的使用,而不是停下来思考或研究 Ruby 是否有一种更具表现力、更简洁的方式,当然,确实如此.

The "correct" answer I originally provided, while it technically works, is not code I would recommend writing. I recall composing my response to fit the question's use of if/else rather than stopping to think or research whether Ruby had a more expressive, succinct way, which, of course, it does.

使用 case 语句:

ar.sort do |a, b| case when a.x < b.x -1 when a.x > b.x 1 else a.y <=> b.y end end

与三元:

ar.sort { |a,b| a.x < b.x ? -1 : (a.x > b.x ? 1 : (a.y <=> b.y)) }

更多推荐

如何在 Ruby 中创建自定义排序方法

本文发布于:2023-11-22 05:41:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1616180.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:自定义   方法   如何在   Ruby

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!