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] }
精彩评论