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? -- Posted via http://www.ruby-forum.com/.
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 Nantz <rails-mailing-list-ARtvInVfO7ksV2N9l4h3zg@public.gmane.org>> > 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? > -- > Posted via http://www.ruby-forum.com/. > > > >--~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group. To post to this group, send email to rubyonrails-talk-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en -~----------~----~----~----~------~----~------~--~---
On May 13, 11:03 am, Shandy Nantz <rails-mailing-l...-ARtvInVfO7ksV2N9l4h3zg@public.gmane.org> 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 marnen-sbuyVjPbboAdnm+yROfE0A@public.gmane.org http://www.marnen.org