Method: String#byteslice
- Defined in:
- string.c
#byteslice(index, length = 1) ⇒ String? #byteslice(range) ⇒ String?
Returns a substring of self, or nil if the substring cannot be constructed.
With integer arguments index and length given, returns the substring beginning at the given index of the given length (if possible), or nil if length is negative or index falls outside of self:
s = '0123456789' # => "0123456789"
s.byteslice(2) # => "2"
s.byteslice(200) # => nil
s.byteslice(4, 3) # => "456"
s.byteslice(4, 30) # => "456789"
s.byteslice(4, -1) # => nil
s.byteslice(40, 2) # => nil
In either case above, counts backwards from the end of self if index is negative:
s = '0123456789' # => "0123456789"
s.byteslice(-4) # => "6"
s.byteslice(-4, 3) # => "678"
With Range argument range given, returns byteslice(range.begin, range.size):
s = '0123456789' # => "0123456789"
s.byteslice(4..6) # => "456"
s.byteslice(-6..-4) # => "456"
s.byteslice(5..2) # => "" # range.size is zero.
s.byteslice(40..42) # => nil
In all cases, a returned string has the same encoding as self:
s.encoding # => #<Encoding:UTF-8>
s.byteslice(4).encoding # => #<Encoding:UTF-8>
6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 |
# File 'string.c', line 6740 static VALUE rb_str_byteslice(int argc, VALUE *argv, VALUE str) { if (argc == 2) { long beg = NUM2LONG(argv[0]); long len = NUM2LONG(argv[1]); return str_byte_substr(str, beg, len, TRUE); } rb_check_arity(argc, 1, 2); return str_byte_aref(str, argv[0]); } |