string.force_encoding(ENCODING::BINARY).slice almost does what you want, 
very efficiently. The problem is that the string will then be marked as 
BINARY. This can be set back, but it may affect operations that run in 
parallel. To expand on this, something like

class String
   def temporarily_binary
     encoding = self.encoding
     self.force_encoding ENCODING::BINARY
     yield
     self.force_encoding encoding
   end
end

would be more general. It would be used like so:

string.temporarily_binary { |s| s.slice(...) }

But this is still not thead-safe.

Regards,   Martin.


On 2011/02/25 17:49, Suraj Kurapati wrote:
>
> Issue #4447 has been reported by Suraj Kurapati.
>
> ----------------------------------------
> Feature #4447: add String#byteslice() method
> http://redmine.ruby-lang.org/issues/4447
>
> Author: Suraj Kurapati
> Status: Open
> Priority: Normal
> Assignee:
> Category:
> Target version:
>
>
> Please add a String#byteslice() method to the Ruby 1.9 core API.
>
> Without that method, I am forced to *inefficiently* perform byte-based
> string slicing by (1) unpacking the entire string into an Array (with
> String#unpack or worse: my_string.bytes.to_a) then (2) slicing that
> Array and finally (3) joining the sliced Array into a string (with
> Array#pack or worse: my_array.map(&:chr).join), all as shown below:
>
>    class String
>      unless method_defined? :byteslice
>        ##
>        # Does the same thing as String#slice but
>        # operates on bytes instead of characters.
>        #
>        def byteslice(*args)
>          unpack('C*').slice(*args).pack('C*')
>        end
>      end
>    end
>
> Thanks for your consideration.
>
>

-- 
#-# Martin J. Drst, Professor, Aoyama Gakuin University
#-# http://www.sw.it.aoyama.ac.jp   mailto:duerst / it.aoyama.ac.jp