按可能为零的属性对对象的 ruby​​ 数组进行排序 [英] sorting a ruby array of objects by an attribute that could be nil

查看:17
本文介绍了按可能为零的属性对对象的 ruby​​ 数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an array of objects that I need to sort by a position attribute that could be an integer or nil, and I need the objects that have the nil position to be at the end of the array. Now, I can force the position to return some value rather than nil so that the array.sort doesn't fail, but if I use 0 as this default, then it puts those objects at the front of the sort. What's the best way to to do this sort? should I just set the nil values to some ridiculously high number that is 'almost' always guaranteed to be at the end? or is there some other way i could cause the array.sort method to put the nil attribute objects at the end of the array? the code looks like this:

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' 设为 1000000000 之类的东西,那么很可能会将它们放在数组的末尾,但我不喜欢这个解决方案,因为它是任意的

now, if i make the 'else' something like 1000000000, then it's most likely gonna put them at the end of the array, but I don't like this solution as it's arbitrary

推荐答案

如何在Child中定义<=>基于category.position 如果 category 存在,并且排序没有 category 的项目总是大于那些有 category 的项目?

How about in Child defining <=> to be based on category.position if category exists, and sorting items without a category as always greater than those with a 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.

Then in Parent you can just call children.sort.

这篇关于按可能为零的属性对对象的 ruby​​ 数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆