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