按属性分选对象的数组红宝石可能是零 [英] sorting a ruby array of objects by an attribute that could be nil

查看:102
本文介绍了按属性分选对象的数组红宝石可能是零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我需要通过这可能是整数或零位置属性进行排序对象的数组,我需要具有零的位置是在数组的末尾的对象。现在,我可以强制返回一些值,而不是零,使得中的Array.sort不会失败的位置,但如果我使用0作为此默认值,然后将其排序的前所说的那些对象。什么是做这样的最佳方式?我应该只设置零值是'几乎'总是保证在年底有些高的离谱号码?或者是有一些其他的方式,我可能会导致Array.sort方法把nil属性对象的数组的末尾?在code是这样的:

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

现在,如果我做了其他类似10亿,那么它很有可能会帮他们在数组的结束,而是因为它是任意的,我不喜欢这个解决方案

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

推荐答案

怎么样在儿童定义&LT; =&GT; 要依据 category.position 如果类别存在,和排序的项目没有一个类别的总是比那些具有类更大

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

然后在,你可以叫 children.sort

这篇关于按属性分选对象的数组红宝石可能是零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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