From: Charles Mills Date: 2004-08-04T09:47:16+09:00 Subject: Re: Fastest way to reverse-process a string? On Aug 3, 2004, at 5:41 PM, Lloyd Zusman wrote: > Joel VanderWerf writes: > >> Lloyd Zusman wrote: >>> In a ruby program I'm writing, I want to parse a string in reverse >>> and >>> feed each of its individual characters through a state machine. >>> A "hammer and tongs" solution looks like this: >>> string.reverse.split(//).each { >>> |ch| >>> feedIntoStateMachine(ch) >>> } >>> However, this seems rather inefficient. Does anyone know of a faster >>> algorithm for this in ruby? >> >> String#each_byte would avoid the creation of the array. > > Thank you very much. > > Does anyone know of a way to avoid 'reverse', as well? I discovered a > 'reverse_each' method for arrays, but there doesn't seem to be a > corresponding String#reverse_each_byte. Without that, I would have to > incur the expense of reversing the string before applying each_byte to > it. > > Any ideas? > You could write one in C... this should work, slight modification of each_byte code... untested: static VALUE rb_str_reverse_each_byte(str) VALUE str; { long i = RSTRING(str)->len; while (i > 0) { i--; rb_yield(INT2FIX(RSTRING(str)->ptr[i] & 0xff)); } return str; } > -- > Lloyd Zusman > ljz@asfast.com > God bless you. > >