我有一个对象数组,我需要按位置属性进行排序,可以是整数或nil,我需要在数组末尾有nil位置的对象.现在,我可以强制位置返回一些值,而不是nil,这样array.排序不会失败,但如果我使用0作为默认值,那么它会将这些对象放在排序的前面.做这种事最好的方法是什么?我是否应该将nil值设置为某个"几乎"总是保证在末尾的高得离谱的数字?或者有没有其他方法可以导致array.排序方法将nil属性对象放在数组的末尾?代码如下所示:

class Parent
  def sorted_children
     children.sort{|a, b| a.position <=> b.position}
  end
end

class Child
  def position
    category ? category.position : #what should the else be??
  end
end

现在,如果我把'else'设为100000000,那么它很可能会把它们放在数组的末尾,但我不喜欢这个解决方案,因为它是任意的

推荐答案

如果category存在,那么在Child中定义<=>category.position为基础,并将没有category的项目排序为总是大于有category的项目,怎么样?

class Child
  # Not strictly necessary, but will define other comparisons based on <=>
  include Comparable   
  def <=> other
    return 0 if !category && !other.category
    return 1 if !category
    return -1 if !other.category
    category.position <=> other.category.position
  end
end

Parent分钟后你可以打children.sort.

Ruby相关问答推荐

MongoDB通过Brew Services";未定义的方法`plist_starting';";

Ruby 中的 Float#floor 和 Float#to_i 有什么区别?

重写 Enum#inject 以在 Ruby 中将符号作为参数

while 语句的主体是块吗?

整数除以负数

这些 Ruby 命名空间约定之间有什么区别?

如何在Ruby中从字符串中go 除前导和尾随引号

Ruby gem 权限被拒绝 /var/lib/gems 使用 Ubuntu

Rails 类 << self

判断字符串是否包含Ruby数组中的任何子字符串

Ruby 的 File.open 给出没有这样的文件或目录 - text.txt (Errno::ENOENT)错误

Ruby 运算符优先级表

如何引用全局变量和类变量?

错误:Windows 的 SASS 安装

在 Ruby 中获取本月的最后一天

在本地覆盖 Vagrant 配置设置(每个开发人员)

为什么表达式 (true == true == true) 会产生语法错误?

如何在器上下文中运行 ruby​​ 脚本?

我可以在 OS X v10.6.8 上升级到当前版本的 Ruby (2.2.3) 吗?

Ruby:如何为数组和哈希制作 IRB 打印 struct