Tuesday, January 22, 2008

Sorting an array

I was following this tutorial that shows you how to sort an array. My action looked like this:

def index
@articles = NodeType.find(1).nodes + NodeType.find(2).nodes
@articles.sort_by { |article| article.updated_at }
end

But that didn't work! It wasn't sorting at all.. at least as far as I could tell. Strange, because this worked:

def index
@articles = NodeType.find(1).nodes + NodeType.find(2).nodes
@articles = @articles.sort_by { |article| article.updated_at }
end

It seems you have to assign it to an object first, before returning it.

3 comments:

Unknown said...

Because sort_by returns the new (sorted) array, not modifies it inplace. Just like sort does.

You could instead use the sort! method, like this:
@articles.sort! {|a1,a2| a1.updated_at <=> a2.updated_at}

Ramon said...

Hehe.. and here I was trying out "sort_by!"

bicz said...

Thanks ... it helped a lot.