Forum: Ruby on Rails Order numbers by value

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Shandy N. (Guest)
on 2009-05-13 19:03
I have this drop-down that get populated with "stuff." As I have
recently found out, this "stuff" will either be all string values or all
numerical values. I have the string values being ordered correctly but
the numerical values are not. For example, this sequence of numbers
7007, 7100, 70100, 7009, 70200 get order as 7007, 7009, 70100, 70200,
7100. Is there a way to treat these strings as numbers instead of
strings and order them as such?
Colin L. (Guest)
on 2009-05-13 19:07
(Received via mailing list)
You could convert them to integer, sort and convert back to string.
There may well be a neater way as this is ruby, I don't know.

2009/5/13 Shandy N. <removed_email_address@domain.invalid>
Marnen L. (Guest)
on 2009-05-13 19:26
(Received via mailing list)
On May 13, 11:03 am, Shandy N. <removed_email_address@domain.invalid>
wrote:
> I have this drop-down that get populated with "stuff." As I have
> recently found out, this "stuff" will either be all string values or all
> numerical values. I have the string values being ordered correctly but
> the numerical values are not. For example, this sequence of numbers
> 7007, 7100, 70100, 7009, 70200 get order as 7007, 7009, 70100, 70200,
> 7100. Is there a way to treat these strings as numbers instead of
> strings and order them as such?

Use a custom sort routine:

['10', '9', '8'].sort #=> ['10', '8', '9']
['10', '9', '8'].sort_by{|x| x.to_i} #=> ['8', '9', '10']
['10', '9', '8'].sort{|a, b| a.to_i <=> b.to_i} #=> ['8', '9', '10']

Does that help?

Best,
--
Marnen Laibow-Koser
removed_email_address@domain.invalid
http://www.marnen.org
This topic is locked and can not be replied to.