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?
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.
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
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.