开发者

Ruby sort_by help unpredictable object attribute

I have a开发者_运维技巧n array with 2 different types of objects. They all have similar properties, like ratings / title etc...

An example is:

array = array.sort_by { |o| [o.type1.rating] }

Sometimes the array has 2 object types type1 and type2 is there any way to sort both of them using the sort_by method?


you can use some metaprogramming for this:

array = array.sort_by { |o| o.respond_to?(:type1) ? [o.type1.rating] : [o.type2.rating] }

That should do the trick.


You can also write something like this

array.sort_by{ |arr| [arr.type1.present? ? arr.type1.rating : arr.type2.rating] }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜