From: Daniel Firu Date: 2009-01-17T08:28:53+09:00 Subject: Re: Convert String to Float if and only if the content of the string are digits On Jan 16, 3:03 pm, Daniel Firu wrote: > Hi All, > > Long time reader -- first time poster.  Basically, I have a bunch of > data that is sucked in from a file.  From reading the pick axe book, > it is my understanding that this data by default will be a string even > if the contents of that string are a bunch of digits.  Well, in the > case that a string is solely composed of digits, I want to convert > them to a float for the purpose of using the <=> operator.  I'll just > go ahead and throw in my method and let you guys tear it a part.  The > goal of the function is to soft my array of arrays based on a > particular element defined by a 'key'.  Maybe there is an easier way > to do this all together. > >   def sort(*keys) options = {} >     regex = "^(\d)*$" >     newData = Array.new >     keys.reverse! >     keys.each do |key| >       newData = @data >       keyIndex = @header.index(key) >       newData.sort! do |entry1, entry2| >         if (!(entry1[keyIndex].match(regex).nil? && entry2 > [keyIndex].match(regex).nil?)) >           print "I found only digits\n" >           entry1[keyIndex].to_f <=> entry2[keyIndex].to_f >         else >           #print "I found something other than digits\n" >           entry1[keyIndex] <=> entry2[keyIndex] >         end >       end >     end >     newTable = Table.new({ >                            :header => @header, >                            :data => newData >                          }) >     newTable >   end > > Thanks in advance for you feedback.  Feel free to be brutal -- I have > thick skin and am still learning. Hi All, I went ahead and changed my method to: def sort(*keys) options = {} regex = Regexp.new('^\d+$') newData = Array.new keys.reverse! keys.each do |key| newData = @data keyIndex = @header.index(key) newData.sort! do |entry1, entry2| if (entry1[keyIndex] =~ regex && entry2[keyIndex] =~ regex) #print "I found only digits\n" entry1[keyIndex].to_f <=> entry2[keyIndex].to_f else #print "I found something other than digits\n" entry1[keyIndex] <=> entry2[keyIndex] end end end newTable = Table.new({ :header => @header, :data => newData }) newTable end Now the question still remains if there is a better way to do this sorting.