From: "Ara.T.Howard" Date: 2005-10-19T23:16:35+09:00 Subject: Re: Array.sort when it's items are String inheritors with redefined <=> works like if not redefined On Wed, 19 Oct 2005, MiG wrote: > Hello, > I want to have a string which, if in array, will be sorted like numbers. I > wrote this: > > ----------------------------------------------------------------------------------------- > > class String2 < String > > def <=> str2 > self.to_i <=> str2.to_i > end > > end > > a = [ String2.new('1'), String2.new('10'), String2.new('5') ] > > puts a.sort.join(',') put the method in Array: harp:~ > cat a.rb class Array def sort_as! map!{|elem| yield elem} sort! self end def sort_as dup.sort! end end a = %w( 1 10 5 ) p a.sort_as{|s| Integer s} p a.sort_as{|s| Float s} p a.sort_as{|s| s.reverse } a.sort_as!{|s| Integer s} p a harp:~ > ruby a.rb ["1", "10", "5"] ["1", "10", "5"] ["1", "10", "5"] [1, 5, 10] this avoids calling to_i, to_f, or whatever multiple times on the same object, which will occur if you use either a spacship (<=>) operator or sort_by approach. hth. -a -- =============================================================================== | email :: ara [dot] t [dot] howard [at] noaa [dot] gov | phone :: 303.497.6469 | anything that contradicts experience and logic should be abandoned. | -- h.h. the 14th dalai lama ===============================================================================