From: Rich Kilmer Date: 2002-03-17T11:38:45+09:00 Subject: RE: sorting large string of records How about this: class StringView attr :offset def initialize(data, offset, len) @data = data @offset = offset @len = len end def <=>(other) @len.times do |i| case @data[@offset+i]<=>@data[other.offset+i] when -1 return -1 when 1 return 1 end end return 0 end def to_s return @data[@offset, @len] end end # build your database and array dbArray = [] database = "00080003000200060007000100040005" len = 4 (database.length/len).times {|i| dbArray << StringView.new(database, i*len, len)} # sort and join puts dbArray.sort.join > -----Original Message----- > From: Ron Jeffries [mailto:ronjeffries@REMOVEacm.org] > Sent: Saturday, March 16, 2002 8:58 PM > To: ruby-talk ML > Subject: sorting large string of records > > > Suppose I have a large string that is really a lot of fixed-size > records joined > together. And suppose that I don't really want to turn it into an array of > strings. (This last is a big supposition: I'm starting to think > maybe I do want > to. But go with me ...) > > I want to sort the records within the big string. > > Here's what I did because it was easy. > > 1. I have an object, StringView, that, given the string, an offset, and a > length, can act like a single record from the big string. I was > already using it > to slice out fields from the "record". > > 2. I implemented <=> on StringView, by slicing the string that it > views and > sending <=> to that (and the string from the argument of course). > > 3. When the StringViews are sorted, I join('') them to get a new string > assembled. > > This has the advantage of being easy but drawbacks include: > > 1. I have to slice the records out anyway > 2. Slices occur more than N times, depending on the O() of Ruby's sort > algorithm. > > Now if I were doing this in C or some language like that, I'd just use my > StringView as a pointer, and look at the bytes of the string without > instantiating a new object. A fairly simple loop over the characters could > implement <=>. > > So ... is there a way to sort my big string without slicing it to smaller > strings? > > Thanks! > > Ronald E Jeffries > http://www.XProgramming.com > http://www.objectmentor.com > I'm giving the best advice I have. You get to decide whether it's > true for you. >