ruby中的自定义排序方法

ale*_*ver 11 ruby ruby-on-rails

我想通过评估两个属性来指定一个自定义块方法来对ruby中的对象数组进行排序.然而,在Google中进行了多次搜索后,如果没有<=>运算符,我就没有任何示例.

这就是我想要做的:比较a和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
Run Code Online (Sandbox Code Playgroud)

这是我的代码(红宝石中的noob,对不起),它不起作用......

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
Run Code Online (Sandbox Code Playgroud)

这个块在一个函数内,所以返回正在退出函数并返回-1 ...我会感谢任何帮助.

亲切的问候.

AJc*_*dez 30

这将为您提供x的升序,然后是y:

points.sort_by{ |p| [p.x, p.y] }
Run Code Online (Sandbox Code Playgroud)


ros*_*sta 16

用案例陈述:

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 
Run Code Online (Sandbox Code Playgroud)

三元:

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

  • 出于可读性/维护原因,不鼓励使用ruby中的多级三元语句. (8认同)