# Order numbers by value

**URL:** <https://www.ruby-forum.com/t/order-numbers-by-value/167886>\
**Category:** Rails\
**Created:** [May 13, 2009, 5:03pm UTC](https://www.ruby-forum.com/t/order-numbers-by-value/167886 "2009-05-13T17:03:31Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![snantz](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/c2a13f/32.png) [@snantz](https://www.ruby-forum.com/u/snantz)\
**Post date:** [May 13, 2009, 5:03pm UTC](https://www.ruby-forum.com/t/order-numbers-by-value/167886/1 "2009-05-13T17:03:31Z")

</div>

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?

---

<div class="post-metadata">

**Author:** ![snantz](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/c2a13f/32.png) [@snantz](https://www.ruby-forum.com/u/snantz)\
**Post date:** [May 13, 2009, 5:07pm UTC](https://www.ruby-forum.com/t/order-numbers-by-value/167886/2 "2009-05-13T17:07:29Z")

</div>

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](mailto:removed_email_address@domain.invalid)

---

<div class="post-metadata">

**Author:** ![snantz](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/c2a13f/32.png) [@snantz](https://www.ruby-forum.com/u/snantz)\
**Post date:** [May 13, 2009, 5:26pm UTC](https://www.ruby-forum.com/t/order-numbers-by-value/167886/3 "2009-05-13T17:26:54Z")

</div>

On May 13, 11:03 am, Shandy N. [removed\_email\_address@domain.invalid](mailto: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](http://www.marnen.org)
