# Sorting different objects

**URL:** <https://www.ruby-forum.com/t/sorting-different-objects/114669>\
**Category:** Rails\
**Created:** [September 17, 2007, 1:24pm UTC](https://www.ruby-forum.com/t/sorting-different-objects/114669 "2007-09-17T13:24:00Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Iain\_A](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/i/6bbea6/32.png) [@Iain\_A](https://www.ruby-forum.com/u/Iain_A)\
**Post date:** [September 17, 2007, 1:24pm UTC](https://www.ruby-forum.com/t/sorting-different-objects/114669/1 "2007-09-17T13:24:00Z")

</div>

hi

I have an array of topics and posts each has an updated\_on field. I  
want to sort the array so in the order of the updated\_on field.

I.e

1 Topic updated on 5 march  
2 Poll updated on 4 march  
3 Topic updated on 6 march  
4 poll updated on 7 march

shoud go 4,3,1,2

my code looks like this  
@topicsAndPolls.sort { |a,b| a.updated\_on \<=\> b.updated\_on} but this  
isnt working. Do I have to define the \<=\> method somewhere. Can I pass  
that in the block aswell?

Thanks

Iain A.

---

<div class="post-metadata">

**Author:** ![Iain\_A](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/i/6bbea6/32.png) [@Iain\_A](https://www.ruby-forum.com/u/Iain_A)\
**Post date:** [September 25, 2007, 11:01pm UTC](https://www.ruby-forum.com/t/sorting-different-objects/114669/2 "2007-09-25T23:01:24Z")

</div>

On Fri, 14 Sep 2007, Iain A. wrote:

> I have an array of topics and posts each has an updated\_on field. I  
> want to sort the array so in the order of the updated\_on field.  
> […]  
> my code looks like this  
> @topicsAndPolls.sort { |a,b| a.updated\_on \<=\> b.updated\_on}  
> [\n inserted] but this  
> isnt working. Do I have to define the \<=\> method somewhere. Can I pass

What do you assign the result of this to? Or did you mean  
@topicsAndPolls.sort! { |a,b| a.updated\_on \<=\> b.updated\_on}

? That’s s/sort/sort!/ in sed parlance, in case the addition of  
one char is as hard for you to spot as for me.

> that in the block aswell?

If updated\_on returns a Date then \<=\> should work. If it doesn’t you’ll  
get a NoMethodError.

```
    Hugh
```

---

<div class="post-metadata">

**Author:** ![Iain\_A](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/i/6bbea6/32.png) [@Iain\_A](https://www.ruby-forum.com/u/Iain_A)\
**Post date:** [September 25, 2007, 11:03pm UTC](https://www.ruby-forum.com/t/sorting-different-objects/114669/3 "2007-09-25T23:03:10Z")

</div>

> shoud go 4,3,1,2
> 
> my code looks like this  
> @topicsAndPolls.sort { |a,b| a.updated\_on \<=\> b.updated\_on} but this  
> isnt working. Do I have to define the \<=\> method somewhere. Can I pass  
> that in the block aswell?

In addition to the other reply, you’re looking for a descendant sort…  
so  
you really want: { |a,b| b.updated\_on \<=\> a.updated\_on}

(not the switching of a and b)

-philip
