method

byteslice

Importance_3
v2_1_10 - Show latest stable - 2 notes - Class: String
byteslice(*args) public

Byte Reference—If passed a single Fixnum, returns a substring of one byte at that position. If passed two Fixnum objects, returns a substring starting at the offset given by the first, and a length given by the second. If given a Range, a substring containing bytes at offsets given by the range is returned. In all three cases, if an offset is negative, it is counted from the end of str. Returns nil if the initial offset falls outside the string, the length is negative, or the beginning of the range is greater than the end. The encoding of the resulted string keeps original encoding.

"hello".byteslice(1)     #=> "e"
"hello".byteslice(-1)    #=> "o"
"hello".byteslice(1, 2)  #=> "el"
"\x80\u3042".byteslice(1, 3) #=> "\u3042"
"\x03\u3042\xff".byteslice(1..3) #=> "\u3042"
Show source
Register or log in to add new notes.
July 13, 2015
1 thank

Correction to previous comment

You’ve misread the documentation, @sandyjoins. If you pass two arguments, the second one is a length argument, not an upper bound.

“Hello there”.byteslice(6, 1) == “t”

July 13, 2015 - (v1_9_3_392)
0 thanks

Important note!

Special cases:

Code example

Test”.byteslice(1, 3) => “est” #both limits inclusive

Test”.byteslice(0, 3) => “Tes” #upper limit exclusive

Test”.byteslice(0..3) => “Test” # Both limits inclusive