How can I sort a list of ActiveRecords by an attribute length?

I think the easy way is to do your sorting from the DB end, as an example in MySQL:

order by LENGTH(sentence) desc

even you could write a scope for this.

Because as I can see, if you are trying to sort it after the DB select, it will be another loop which is unnecessary.


Sameera207 has the right idea, but giving you the answer as ruby code.

Hint.where("sentence LIKE ?","%你%").order("LENGTH(sentence) ASC")

This will solve your problem

Perhaps you want a method like this;

def shortest_example(word)
  Hint.where("sentence LIKE ?", "%#{word}%").order("LENGTH(sentence) ASC").first
end