Support for the Ruby 2.4 series has ended. See here for reference.
A String
object holds and manipulates an arbitrary sequence of bytes, typically representing characters. String
objects may be created using String::new
or as literals.
Because of aliasing issues, users of strings should be aware of the methods that modify the contents of a String
object. Typically, methods with names ending in “!'' modify their receiver, while those without a “!'' return a new String
. However, there are exceptions, such as String#[]=
.
Returns a new string object containing a copy of str.
The optional enc argument specifies the encoding of the new string. If not specified, the encoding of str (or ASCII-8BIT, if str is not specified) is used.
The optional size argument specifies the size of internal buffer. This may improve performance, when the string will be concatenated many times (and call many realloc).
static VALUE rb_str_init(int argc, VALUE *argv, VALUE str) { static ID keyword_ids[2]; VALUE orig, opt, venc, vcapa; VALUE kwargs[2]; rb_encoding *enc = 0; int n; if (!keyword_ids[0]) { keyword_ids[0] = rb_id_encoding(); CONST_ID(keyword_ids[1], "capacity"); } n = rb_scan_args(argc, argv, "01:", &orig, &opt); if (!NIL_P(opt)) { rb_get_kwargs(opt, keyword_ids, 0, 2, kwargs); venc = kwargs[0]; vcapa = kwargs[1]; if (venc != Qundef && !NIL_P(venc)) { enc = rb_to_encoding(venc); } if (vcapa != Qundef && !NIL_P(vcapa)) { long capa = NUM2LONG(vcapa); long len = 0; int termlen = enc ? rb_enc_mbminlen(enc) : 1; if (capa < STR_BUF_MIN_SIZE) { capa = STR_BUF_MIN_SIZE; } if (n == 1) { StringValue(orig); len = RSTRING_LEN(orig); if (capa < len) { capa = len; } if (orig == str) n = 0; } str_modifiable(str); if (STR_EMBED_P(str)) { /* make noembed always */ RSTRING(str)->as.heap.ptr = ALLOC_N(char, (size_t)capa + termlen); } else if (STR_HEAP_SIZE(str) != (size_t)capa + termlen) { REALLOC_N(RSTRING(str)->as.heap.ptr, char, (size_t)capa + termlen); } RSTRING(str)->as.heap.len = len; TERM_FILL(&RSTRING(str)->as.heap.ptr[len], termlen); if (n == 1) { memcpy(RSTRING(str)->as.heap.ptr, RSTRING_PTR(orig), len); rb_enc_cr_str_exact_copy(str, orig); } FL_SET(str, STR_NOEMBED); RSTRING(str)->as.heap.aux.capa = capa; } else if (n == 1) { rb_str_replace(str, orig); } if (enc) { rb_enc_associate(str, enc); ENC_CODERANGE_CLEAR(str); } } else if (n == 1) { rb_str_replace(str, orig); } return str; }
Format—Uses str as a format specification, and returns the result of applying it to arg. If the format specification contains more than one substitution, then arg must be an Array
or Hash
containing the values to be substituted. See Kernel::sprintf
for details of the format string.
"%05d" % 123 #=> "00123" "%-5s: %08x" % [ "ID", self.object_id ] #=> "ID : 200e14d6" "foo = %{foo}" % { :foo => 'bar' } #=> "foo = bar"
static VALUE rb_str_format_m(VALUE str, VALUE arg) { VALUE tmp = rb_check_array_type(arg); if (!NIL_P(tmp)) { VALUE rv = rb_str_format(RARRAY_LENINT(tmp), RARRAY_CONST_PTR(tmp), str); RB_GC_GUARD(tmp); return rv; } return rb_str_format(1, &arg, str); }
Copy — Returns a new String
containing integer
copies of the receiver. integer
must be greater than or equal to 0.
"Ho! " * 3 #=> "Ho! Ho! Ho! " "Ho! " * 0 #=> ""
VALUE rb_str_times(VALUE str, VALUE times) { VALUE str2; long n, len; char *ptr2; int termlen; if (times == INT2FIX(1)) { return rb_str_dup(str); } if (times == INT2FIX(0)) { str2 = str_alloc(rb_obj_class(str)); rb_enc_copy(str2, str); OBJ_INFECT(str2, str); return str2; } len = NUM2LONG(times); if (len < 0) { rb_raise(rb_eArgError, "negative argument"); } if (len && LONG_MAX/len < RSTRING_LEN(str)) { rb_raise(rb_eArgError, "argument too big"); } len *= RSTRING_LEN(str); termlen = TERM_LEN(str); str2 = str_new0(rb_obj_class(str), 0, len, termlen); ptr2 = RSTRING_PTR(str2); if (len) { n = RSTRING_LEN(str); memcpy(ptr2, RSTRING_PTR(str), n); while (n <= len/2) { memcpy(ptr2 + n, ptr2, n); n *= 2; } memcpy(ptr2 + n, ptr2, len-n); } STR_SET_LEN(str2, len); TERM_FILL(&ptr2[len], termlen); OBJ_INFECT(str2, str); rb_enc_cr_str_copy_for_substr(str2, str); return str2; }
Concatenation—Returns a new String
containing other_str concatenated to str.
"Hello from " + self.to_s #=> "Hello from main"
VALUE rb_str_plus(VALUE str1, VALUE str2) { VALUE str3; rb_encoding *enc; char *ptr1, *ptr2, *ptr3; long len1, len2; int termlen; StringValue(str2); enc = rb_enc_check_str(str1, str2); RSTRING_GETMEM(str1, ptr1, len1); RSTRING_GETMEM(str2, ptr2, len2); termlen = rb_enc_mbminlen(enc); if (len1 > LONG_MAX - len2) { rb_raise(rb_eArgError, "string size too big"); } str3 = str_new0(rb_cString, 0, len1+len2, termlen); ptr3 = RSTRING_PTR(str3); memcpy(ptr3, ptr1, len1); memcpy(ptr3+len1, ptr2, len2); TERM_FILL(&ptr3[len1+len2], termlen); FL_SET_RAW(str3, OBJ_TAINTED_RAW(str1) | OBJ_TAINTED_RAW(str2)); ENCODING_CODERANGE_SET(str3, rb_enc_to_index(enc), ENC_CODERANGE_AND(ENC_CODERANGE(str1), ENC_CODERANGE(str2))); RB_GC_GUARD(str1); RB_GC_GUARD(str2); return str3; }
If the string is frozen, then return duplicated mutable string.
If the string is not frozen, then return the string itself.
static VALUE str_uplus(VALUE str) { if (OBJ_FROZEN(str)) { return rb_str_dup(str); } else { return str; } }
If the string is frozen, then return the string itself.
If the string is not frozen, then duplicate the string freeze it and return it.
static VALUE str_uminus(VALUE str) { if (OBJ_FROZEN(str)) { return str; } else { return rb_str_freeze(rb_str_dup(str)); } }
Append—Concatenates the given object to str. If the object is an Integer
, it is considered as a codepoint, and is converted to a character before concatenation. Concat can take multiple arguments. All the arguments are concatenated in order.
a = "hello " a << "world" #=> "hello world" a.concat(33) #=> "hello world!" a #=> "hello world!" b = "sn" b.concat(b, b) #=> "snsnsn"
VALUE rb_str_concat(VALUE str1, VALUE str2) { unsigned int code; rb_encoding *enc = STR_ENC_GET(str1); int encidx; if (RB_INTEGER_TYPE_P(str2)) { if (rb_num_to_uint(str2, &code) == 0) { } else if (FIXNUM_P(str2)) { rb_raise(rb_eRangeError, "%ld out of char range", FIX2LONG(str2)); } else { rb_raise(rb_eRangeError, "bignum out of char range"); } } else { return rb_str_append(str1, str2); } encidx = rb_enc_to_index(enc); if (encidx == ENCINDEX_ASCII || encidx == ENCINDEX_US_ASCII) { /* US-ASCII automatically extended to ASCII-8BIT */ char buf[1]; buf[0] = (char)code; if (code > 0xFF) { rb_raise(rb_eRangeError, "%u out of char range", code); } rb_str_cat(str1, buf, 1); if (encidx == ENCINDEX_US_ASCII && code > 127) { rb_enc_associate_index(str1, ENCINDEX_ASCII); ENC_CODERANGE_SET(str1, ENC_CODERANGE_VALID); } } else { long pos = RSTRING_LEN(str1); int cr = ENC_CODERANGE(str1); int len; char *buf; switch (len = rb_enc_codelen(code, enc)) { case ONIGERR_INVALID_CODE_POINT_VALUE: rb_raise(rb_eRangeError, "invalid codepoint 0x%X in %s", code, rb_enc_name(enc)); break; case ONIGERR_TOO_BIG_WIDE_CHAR_VALUE: case 0: rb_raise(rb_eRangeError, "%u out of char range", code); break; } buf = ALLOCA_N(char, len + 1); rb_enc_mbcput(code, buf, enc); if (rb_enc_precise_mbclen(buf, buf + len + 1, enc) != len) { rb_raise(rb_eRangeError, "invalid codepoint 0x%X in %s", code, rb_enc_name(enc)); } rb_str_resize(str1, pos+len); memcpy(RSTRING_PTR(str1) + pos, buf, len); if (cr == ENC_CODERANGE_7BIT && code > 127) cr = ENC_CODERANGE_VALID; ENC_CODERANGE_SET(str1, cr); } return str1; }
Comparison—Returns -1, 0, +1 or nil depending on whether string
is less than, equal to, or greater than other_string
.
nil
is returned if the two values are incomparable.
If the strings are of different lengths, and the strings are equal when compared up to the shortest length, then the longer string is considered greater than the shorter one.
<=>
is the basis for the methods <
, <=
, >
, >=
, and between?
, included from module Comparable
. The method String#== does not use Comparable#==.
"abcdef" <=> "abcde" #=> 1 "abcdef" <=> "abcdef" #=> 0 "abcdef" <=> "abcdefg" #=> -1 "abcdef" <=> "ABCDEF" #=> 1 "abcdef" <=> 1 #=> nil
static VALUE rb_str_cmp_m(VALUE str1, VALUE str2) { int result; if (!RB_TYPE_P(str2, T_STRING)) { VALUE tmp = rb_check_funcall(str2, idTo_str, 0, 0); if (RB_TYPE_P(tmp, T_STRING)) { result = rb_str_cmp(str1, tmp); } else { return rb_invcmp(str1, str2); } } else { result = rb_str_cmp(str1, str2); } return INT2FIX(result); }
Equality—Returns whether str
== obj
, similar to Object#==.
If obj
is not an instance of String
but responds to to_str
, then the two strings are compared using obj.==
.
Otherwise, returns similarly to String#eql?
, comparing length and content.
VALUE rb_str_equal(VALUE str1, VALUE str2) { if (str1 == str2) return Qtrue; if (!RB_TYPE_P(str2, T_STRING)) { if (!rb_respond_to(str2, idTo_str)) { return Qfalse; } return rb_equal(str2, str1); } return str_eql(str1, str2); }
Equality—Returns whether str
== obj
, similar to Object#==.
If obj
is not an instance of String
but responds to to_str
, then the two strings are compared using obj.==
.
Otherwise, returns similarly to String#eql?
, comparing length and content.
VALUE rb_str_equal(VALUE str1, VALUE str2) { if (str1 == str2) return Qtrue; if (!RB_TYPE_P(str2, T_STRING)) { if (!rb_respond_to(str2, idTo_str)) { return Qfalse; } return rb_equal(str2, str1); } return str_eql(str1, str2); }
Match—If obj is a Regexp
, use it as a pattern to match against str,and returns the position the match starts, or nil
if there is no match. Otherwise, invokes obj.=~, passing str as an argument. The default =~
in Object
returns nil
.
Note: str =~ regexp
is not the same as regexp =~ str
. Strings captured from named capture groups are assigned to local variables only in the second case.
"cat o' 9 tails" =~ /\d/ #=> 7 "cat o' 9 tails" =~ 9 #=> nil
static VALUE rb_str_match(VALUE x, VALUE y) { if (SPECIAL_CONST_P(y)) goto generic; switch (BUILTIN_TYPE(y)) { case T_STRING: rb_raise(rb_eTypeError, "type mismatch: String given"); case T_REGEXP: return rb_reg_match(y, x); generic: default: return rb_funcall(y, idEqTilde, 1, x); } }
Element Reference — If passed a single index
, returns a substring of one character at that index. If passed a start
index and a length
, returns a substring containing length
characters starting at the start
index. If passed a range
, its beginning and end are interpreted as offsets delimiting the substring to be returned.
In these three cases, if an index is negative, it is counted from the end of the string. For the start
and range
cases the starting index is just before a character and an index matching the string's size. Additionally, an empty string is returned when the starting index for a character range is at the end of the string.
Returns nil
if the initial index falls outside the string or the length is negative.
If a Regexp
is supplied, the matching portion of the string is returned. If a capture
follows the regular expression, which may be a capture group index or name, follows the regular expression that component of the MatchData
is returned instead.
If a match_str
is given, that string is returned if it occurs in the string.
Returns nil
if the regular expression does not match or the match string cannot be found.
a = "hello there" a[1] #=> "e" a[2, 3] #=> "llo" a[2..3] #=> "ll" a[-3, 2] #=> "er" a[7..-2] #=> "her" a[-4..-2] #=> "her" a[-2..-4] #=> "" a[11, 0] #=> "" a[11] #=> nil a[12, 0] #=> nil a[12..-1] #=> nil a[/[aeiou](.)\1/] #=> "ell" a[/[aeiou](.)\1/, 0] #=> "ell" a[/[aeiou](.)\1/, 1] #=> "l" a[/[aeiou](.)\1/, 2] #=> nil a[/(?<vowel>[aeiou])(?<non_vowel>[^aeiou])/, "non_vowel"] #=> "l" a[/(?<vowel>[aeiou])(?<non_vowel>[^aeiou])/, "vowel"] #=> "e" a["lo"] #=> "lo" a["bye"] #=> nil
static VALUE rb_str_aref_m(int argc, VALUE *argv, VALUE str) { if (argc == 2) { if (RB_TYPE_P(argv[0], T_REGEXP)) { return rb_str_subpat(str, argv[0], argv[1]); } else { long beg = NUM2LONG(argv[0]); long len = NUM2LONG(argv[1]); return rb_str_substr(str, beg, len); } } rb_check_arity(argc, 1, 2); return rb_str_aref(str, argv[0]); }
Element Assignment—Replaces some or all of the content of str. The portion of the string affected is determined using the same criteria as String#[]
. If the replacement string is not the same length as the text it is replacing, the string will be adjusted accordingly. If the regular expression or string is used as the index doesn't match a position in the string, IndexError
is raised. If the regular expression form is used, the optional second Integer
allows you to specify which portion of the match to replace (effectively using the MatchData
indexing rules. The forms that take an Integer
will raise an IndexError
if the value is out of range; the Range
form will raise a RangeError
, and the Regexp
and String
will raise an IndexError
on negative match.
static VALUE rb_str_aset_m(int argc, VALUE *argv, VALUE str) { if (argc == 3) { if (RB_TYPE_P(argv[0], T_REGEXP)) { rb_str_subpat_set(str, argv[0], argv[1], argv[2]); } else { rb_str_splice(str, NUM2LONG(argv[0]), NUM2LONG(argv[1]), argv[2]); } return argv[2]; } rb_check_arity(argc, 2, 3); return rb_str_aset(str, argv[0], argv[1]); }
Returns true for a string which has only ASCII characters.
"abc".force_encoding("UTF-8").ascii_only? #=> true "abc\u{6666}".force_encoding("UTF-8").ascii_only? #=> false
static VALUE rb_str_is_ascii_only_p(VALUE str) { int cr = rb_enc_str_coderange(str); return cr == ENC_CODERANGE_7BIT ? Qtrue : Qfalse; }
Returns a copied string whose encoding is ASCII-8BIT.
static VALUE rb_str_b(VALUE str) { VALUE str2 = str_alloc(rb_cString); str_replace_shared_without_enc(str2, str); OBJ_INFECT_RAW(str2, str); ENC_CODERANGE_CLEAR(str2); return str2; }
Returns an array of bytes in str. This is a shorthand for str.each_byte.to_a
.
If a block is given, which is a deprecated form, works the same as each_byte
.
static VALUE rb_str_bytes(VALUE str) { return rb_str_enumerate_bytes(str, 1); }
Returns the length of str
in bytes.
"\x80\u3042".bytesize #=> 4 "hello".bytesize #=> 5
static VALUE rb_str_bytesize(VALUE str) { return LONG2NUM(RSTRING_LEN(str)); }
Byte Reference—If passed a single Integer
, returns a substring of one byte at that position. If passed two Integer
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"
static VALUE rb_str_byteslice(int argc, VALUE *argv, VALUE str) { if (argc == 2) { long beg = NUM2LONG(argv[0]); long end = NUM2LONG(argv[1]); return str_byte_substr(str, beg, end, TRUE); } rb_check_arity(argc, 1, 2); return str_byte_aref(str, argv[0]); }
Returns a copy of str with the first character converted to uppercase and the remainder to lowercase.
See String#downcase
for meaning of options
and use with different encodings.
"hello".capitalize #=> "Hello" "HELLO".capitalize #=> "Hello" "123ABC".capitalize #=> "123abc"
static VALUE rb_str_capitalize(int argc, VALUE *argv, VALUE str) { str = rb_str_dup(str); rb_str_capitalize_bang(argc, argv, str); return str; }
Modifies str by converting the first character to uppercase and the remainder to lowercase. Returns nil
if no changes are made.
See String#downcase
for meaning of options
and use with different encodings.
a = "hello" a.capitalize! #=> "Hello" a #=> "Hello" a.capitalize! #=> nil
static VALUE rb_str_capitalize_bang(int argc, VALUE *argv, VALUE str) { rb_encoding *enc; OnigCaseFoldType flags = ONIGENC_CASE_UPCASE | ONIGENC_CASE_TITLECASE; flags = check_case_options(argc, argv, flags); str_modify_keep_cr(str); enc = STR_ENC_GET(str); rb_str_check_dummy_enc(enc); if (RSTRING_LEN(str) == 0 || !RSTRING_PTR(str)) return Qnil; if (flags&ONIGENC_CASE_ASCII_ONLY) rb_str_ascii_casemap(str, &flags, enc); else str_shared_replace(str, rb_str_casemap(str, &flags, enc)); if (ONIGENC_CASE_MODIFIED&flags) return str; return Qnil; }
Case-insensitive version of String#<=>
. Currently, case-insensitivity only works on characters A-Z/a-z, not all of Unicode. This is different from casecmp?
.
"abcdef".casecmp("abcde") #=> 1 "aBcDeF".casecmp("abcdef") #=> 0 "abcdef".casecmp("abcdefg") #=> -1 "abcdef".casecmp("ABCDEF") #=> 0
static VALUE rb_str_casecmp(VALUE str1, VALUE str2) { long len; rb_encoding *enc; char *p1, *p1end, *p2, *p2end; StringValue(str2); enc = rb_enc_compatible(str1, str2); if (!enc) { return Qnil; } p1 = RSTRING_PTR(str1); p1end = RSTRING_END(str1); p2 = RSTRING_PTR(str2); p2end = RSTRING_END(str2); if (single_byte_optimizable(str1) && single_byte_optimizable(str2)) { while (p1 < p1end && p2 < p2end) { if (*p1 != *p2) { unsigned int c1 = TOUPPER(*p1 & 0xff); unsigned int c2 = TOUPPER(*p2 & 0xff); if (c1 != c2) return INT2FIX(c1 < c2 ? -1 : 1); } p1++; p2++; } } else { while (p1 < p1end && p2 < p2end) { int l1, c1 = rb_enc_ascget(p1, p1end, &l1, enc); int l2, c2 = rb_enc_ascget(p2, p2end, &l2, enc); if (0 <= c1 && 0 <= c2) { c1 = TOUPPER(c1); c2 = TOUPPER(c2); if (c1 != c2) return INT2FIX(c1 < c2 ? -1 : 1); } else { int r; l1 = rb_enc_mbclen(p1, p1end, enc); l2 = rb_enc_mbclen(p2, p2end, enc); len = l1 < l2 ? l1 : l2; r = memcmp(p1, p2, len); if (r != 0) return INT2FIX(r < 0 ? -1 : 1); if (l1 != l2) return INT2FIX(l1 < l2 ? -1 : 1); } p1 += l1; p2 += l2; } } if (RSTRING_LEN(str1) == RSTRING_LEN(str2)) return INT2FIX(0); if (RSTRING_LEN(str1) > RSTRING_LEN(str2)) return INT2FIX(1); return INT2FIX(-1); }
Returns true if str and other_other_str are equal after Unicode case folding, false if they are not equal, and nil if other_str is not a string.
"abcdef".casecmp?("abcde") #=> false "aBcDeF".casecmp?("abcdef") #=> true "abcdef".casecmp?("abcdefg") #=> false "abcdef".casecmp?("ABCDEF") #=> true "\u{e4 f6 fc}".casecmp?("\u{c4 d6 dc}") #=> true
static VALUE rb_str_casecmp_p(VALUE str1, VALUE str2) { rb_encoding *enc; VALUE folded_str1, folded_str2; VALUE fold_opt = sym_fold; StringValue(str2); enc = rb_enc_compatible(str1, str2); if (!enc) { return Qnil; } folded_str1 = rb_str_downcase(1, &fold_opt, str1); folded_str2 = rb_str_downcase(1, &fold_opt, str2); return rb_str_eql(folded_str1, folded_str2); }
Centers str
in width
. If width
is greater than the length of str
, returns a new String
of length width
with str
centered and padded with padstr
; otherwise, returns str
.
"hello".center(4) #=> "hello" "hello".center(20) #=> " hello " "hello".center(20, '123') #=> "1231231hello12312312"
static VALUE rb_str_center(int argc, VALUE *argv, VALUE str) { return rb_str_justify(argc, argv, str, 'c'); }
Returns an array of characters in str. This is a shorthand for str.each_char.to_a
.
If a block is given, which is a deprecated form, works the same as each_char
.
static VALUE rb_str_chars(VALUE str) { return rb_str_enumerate_chars(str, 1); }
Returns a new String
with the given record separator removed from the end of str (if present). If $/
has not been changed from the default Ruby record separator, then chomp
also removes carriage return characters (that is it will remove \n
, \r
, and \r\n
). If $/
is an empty string, it will remove all trailing newlines from the string.
"hello".chomp #=> "hello" "hello\n".chomp #=> "hello" "hello\r\n".chomp #=> "hello" "hello\n\r".chomp #=> "hello\n" "hello\r".chomp #=> "hello" "hello \n there".chomp #=> "hello \n there" "hello".chomp("llo") #=> "he" "hello\r\n\r\n".chomp('') #=> "hello" "hello\r\n\r\r\n".chomp('') #=> "hello\r\n\r"
static VALUE rb_str_chomp(int argc, VALUE *argv, VALUE str) { VALUE rs = chomp_rs(argc, argv); if (NIL_P(rs)) return rb_str_dup(str); return rb_str_subseq(str, 0, chompped_length(str, rs)); }
Modifies str in place as described for String#chomp
, returning str, or nil
if no modifications were made.
static VALUE rb_str_chomp_bang(int argc, VALUE *argv, VALUE str) { VALUE rs; str_modify_keep_cr(str); if (RSTRING_LEN(str) == 0) return Qnil; rs = chomp_rs(argc, argv); if (NIL_P(rs)) return Qnil; return rb_str_chomp_string(str, rs); }
Returns a new String
with the last character removed. If the string ends with \r\n
, both characters are removed. Applying chop
to an empty string returns an empty string. String#chomp
is often a safer alternative, as it leaves the string unchanged if it doesn't end in a record separator.
"string\r\n".chop #=> "string" "string\n\r".chop #=> "string\n" "string\n".chop #=> "string" "string".chop #=> "strin" "x".chop.chop #=> ""
static VALUE rb_str_chop(VALUE str) { return rb_str_subseq(str, 0, chopped_length(str)); }
Processes str as for String#chop
, returning str, or nil
if str is the empty string. See also String#chomp!
.
static VALUE rb_str_chop_bang(VALUE str) { str_modify_keep_cr(str); if (RSTRING_LEN(str) > 0) { long len; len = chopped_length(str); STR_SET_LEN(str, len); TERM_FILL(&RSTRING_PTR(str)[len], TERM_LEN(str)); if (ENC_CODERANGE(str) != ENC_CODERANGE_7BIT) { ENC_CODERANGE_CLEAR(str); } return str; } return Qnil; }
Returns a one-character string at the beginning of the string.
a = "abcde" a.chr #=> "a"
static VALUE rb_str_chr(VALUE str) { return rb_str_substr(str, 0, 1); }
Makes string empty.
a = "abcde" a.clear #=> ""
static VALUE rb_str_clear(VALUE str) { str_discard(str); STR_SET_EMBED(str); STR_SET_EMBED_LEN(str, 0); RSTRING_PTR(str)[0] = 0; if (rb_enc_asciicompat(STR_ENC_GET(str))) ENC_CODERANGE_SET(str, ENC_CODERANGE_7BIT); else ENC_CODERANGE_SET(str, ENC_CODERANGE_VALID); return str; }
Returns an array of the Integer
ordinals of the characters in str. This is a shorthand for str.each_codepoint.to_a
.
If a block is given, which is a deprecated form, works the same as each_codepoint
.
static VALUE rb_str_codepoints(VALUE str) { return rb_str_enumerate_codepoints(str, 1); }
Append—Concatenates the given object to str. If the object is an Integer
, it is considered as a codepoint, and is converted to a character before concatenation. Concat can take multiple arguments. All the arguments are concatenated in order.
a = "hello " a << "world" #=> "hello world" a.concat(33) #=> "hello world!" a #=> "hello world!" b = "sn" b.concat(b, b) #=> "snsnsn"
static VALUE rb_str_concat_multi(int argc, VALUE *argv, VALUE str) { str_modifiable(str); if (argc > 0) { int i; VALUE arg_str = rb_str_tmp_new(0); rb_enc_copy(arg_str, str); for (i = 0; i < argc; i++) { rb_str_concat(arg_str, argv[i]); } rb_str_buf_append(str, arg_str); } return str; }
Each other_str
parameter defines a set of characters to count. The intersection of these sets defines the characters to count in str
. Any other_str
that starts with a caret ^
is negated. The sequence c1-c2
means all characters between c1 and c2. The backslash character \
can be used to escape ^
or -
and is otherwise ignored unless it appears at the end of a sequence or the end of a other_str
.
a = "hello world" a.count "lo" #=> 5 a.count "lo", "o" #=> 2 a.count "hello", "^l" #=> 4 a.count "ej-m" #=> 4 "hello^world".count "\\^aeiou" #=> 4 "hello-world".count "a\\-eo" #=> 4 c = "hello world\\r\\n" c.count "\\" #=> 2 c.count "\\A" #=> 0 c.count "X-\\w" #=> 3
static VALUE rb_str_count(int argc, VALUE *argv, VALUE str) { char table[TR_TABLE_SIZE]; rb_encoding *enc = 0; VALUE del = 0, nodel = 0, tstr; char *s, *send; int i; int ascompat; rb_check_arity(argc, 1, UNLIMITED_ARGUMENTS); tstr = argv[0]; StringValue(tstr); enc = rb_enc_check(str, tstr); if (argc == 1) { const char *ptstr; if (RSTRING_LEN(tstr) == 1 && rb_enc_asciicompat(enc) && (ptstr = RSTRING_PTR(tstr), ONIGENC_IS_ALLOWED_REVERSE_MATCH(enc, (const unsigned char *)ptstr, (const unsigned char *)ptstr+1)) && !is_broken_string(str)) { int n = 0; int clen; unsigned char c = rb_enc_codepoint_len(ptstr, ptstr+1, &clen, enc); s = RSTRING_PTR(str); if (!s || RSTRING_LEN(str) == 0) return INT2FIX(0); send = RSTRING_END(str); while (s < send) { if (*(unsigned char*)s++ == c) n++; } return INT2NUM(n); } } tr_setup_table(tstr, table, TRUE, &del, &nodel, enc); for (i=1; i<argc; i++) { tstr = argv[i]; StringValue(tstr); enc = rb_enc_check(str, tstr); tr_setup_table(tstr, table, FALSE, &del, &nodel, enc); } s = RSTRING_PTR(str); if (!s || RSTRING_LEN(str) == 0) return INT2FIX(0); send = RSTRING_END(str); ascompat = rb_enc_asciicompat(enc); i = 0; while (s < send) { unsigned int c; if (ascompat && (c = *(unsigned char*)s) < 0x80) { if (table[c]) { i++; } s++; } else { int clen; c = rb_enc_codepoint_len(s, send, &clen, enc); if (tr_find(c, table, del, nodel)) { i++; } s += clen; } } return INT2NUM(i); }
Applies a one-way cryptographic hash to str by invoking the standard library function crypt(3)
with the given salt string. While the format and the result are system and implementation dependent, using a salt matching the regular expression \A[a-zA-Z0-9./]{2}
should be valid and safe on any platform, in which only the first two characters are significant.
This method is for use in system specific scripts, so if you want a cross-platform hash function consider using Digest or OpenSSL instead.
static VALUE rb_str_crypt(VALUE str, VALUE salt) { #ifdef HAVE_CRYPT_R struct crypt_data data; #else extern char *crypt(const char *, const char *); #endif VALUE result; const char *s, *saltp; char *res; #ifdef BROKEN_CRYPT char salt_8bit_clean[3]; #endif StringValue(salt); mustnot_wchar(str); mustnot_wchar(salt); if (RSTRING_LEN(salt) < 2) { short_salt: rb_raise(rb_eArgError, "salt too short (need >=2 bytes)"); } s = StringValueCStr(str); saltp = RSTRING_PTR(salt); if (!saltp[0] || !saltp[1]) goto short_salt; #ifdef BROKEN_CRYPT if (!ISASCII((unsigned char)saltp[0]) || !ISASCII((unsigned char)saltp[1])) { salt_8bit_clean[0] = saltp[0] & 0x7f; salt_8bit_clean[1] = saltp[1] & 0x7f; salt_8bit_clean[2] = '\0'; saltp = salt_8bit_clean; } #endif #ifdef HAVE_CRYPT_R # ifdef HAVE_STRUCT_CRYPT_DATA_INITIALIZED data.initialized = 0; # endif res = crypt_r(s, saltp, &data); #else res = crypt(s, saltp); #endif if (!res) { rb_sys_fail("crypt"); } result = rb_str_new_cstr(res); FL_SET_RAW(result, OBJ_TAINTED_RAW(str) | OBJ_TAINTED_RAW(salt)); return result; }
Returns a copy of str with all characters in the intersection of its arguments deleted. Uses the same rules for building the set of characters as String#count
.
"hello".delete "l","lo" #=> "heo" "hello".delete "lo" #=> "he" "hello".delete "aeiou", "^e" #=> "hell" "hello".delete "ej-m" #=> "ho"
static VALUE rb_str_delete(int argc, VALUE *argv, VALUE str) { str = rb_str_dup(str); rb_str_delete_bang(argc, argv, str); return str; }
Performs a delete
operation in place, returning str, or nil
if str was not modified.
static VALUE rb_str_delete_bang(int argc, VALUE *argv, VALUE str) { char squeez[TR_TABLE_SIZE]; rb_encoding *enc = 0; char *s, *send, *t; VALUE del = 0, nodel = 0; int modify = 0; int i, ascompat, cr; if (RSTRING_LEN(str) == 0 || !RSTRING_PTR(str)) return Qnil; rb_check_arity(argc, 1, UNLIMITED_ARGUMENTS); for (i=0; i<argc; i++) { VALUE s = argv[i]; StringValue(s); enc = rb_enc_check(str, s); tr_setup_table(s, squeez, i==0, &del, &nodel, enc); } str_modify_keep_cr(str); ascompat = rb_enc_asciicompat(enc); s = t = RSTRING_PTR(str); send = RSTRING_END(str); cr = ascompat ? ENC_CODERANGE_7BIT : ENC_CODERANGE_VALID; while (s < send) { unsigned int c; int clen; if (ascompat && (c = *(unsigned char*)s) < 0x80) { if (squeez[c]) { modify = 1; } else { if (t != s) *t = c; t++; } s++; } else { c = rb_enc_codepoint_len(s, send, &clen, enc); if (tr_find(c, squeez, del, nodel)) { modify = 1; } else { if (t != s) rb_enc_mbcput(c, t, enc); t += clen; if (cr == ENC_CODERANGE_7BIT) cr = ENC_CODERANGE_VALID; } s += clen; } } TERM_FILL(t, TERM_LEN(str)); STR_SET_LEN(str, t - RSTRING_PTR(str)); ENC_CODERANGE_SET(str, cr); if (modify) return str; return Qnil; }
Returns a copy of str with all uppercase letters replaced with their lowercase counterparts. Which letters exactly are replaced, and by which other letters, depends on the presence or absence of options, and on the encoding
of the string.
The meaning of the options
is as follows:
Full Unicode case mapping, suitable for most languages (see :turkic and :lithuanian options below for exceptions). Context-dependent case mapping as described in Table 3-14 of the Unicode standard is currently not supported.
Only the ASCII region, i.e. the characters “A'' to “Z'' and “a'' to “z'', are affected. This option cannot be combined with any other option.
Full Unicode case mapping, adapted for Turkic languages (Turkish, Aserbaijani,…). This means that upper case I is mapped to lower case dotless i, and so on.
Currently, just full Unicode case mapping. In the future, full Unicode case mapping adapted for Lithuanian (keeping the dot on the lower case i even if there is an accent on top).
Only available on downcase
and downcase!
. Unicode case folding, which is more far-reaching than Unicode case mapping. This option currently cannot be combined with any other option (i.e. there is currenty no variant for turkic languages).
Please note that several assumptions that are valid for ASCII-only case conversions do not hold for more general case conversions. For example, the length of the result may not be the same as the length of the input (neither in characters nor in bytes), some roundtrip assumptions (e.g. str.downcase == str.upcase.downcase) may not apply, and Unicode normalization (i.e. String#unicode_normalize) is not necessarily maintained by case mapping operations.
Non-ASCII case mapping/folding is currently supported for UTF-8, UTF-16BE/LE, UTF-32BE/LE, and ISO-8859-1~16 Strings/Symbols. This support will be extended to other encodings.
"hEllO".downcase #=> "hello"
static VALUE rb_str_downcase(int argc, VALUE *argv, VALUE str) { str = rb_str_dup(str); rb_str_downcase_bang(argc, argv, str); return str; }
Downcases the contents of str, returning nil
if no changes were made.
See String#downcase
for meaning of options
and use with different encodings.
static VALUE rb_str_downcase_bang(int argc, VALUE *argv, VALUE str) { rb_encoding *enc; OnigCaseFoldType flags = ONIGENC_CASE_DOWNCASE; flags = check_case_options(argc, argv, flags); str_modify_keep_cr(str); enc = STR_ENC_GET(str); rb_str_check_dummy_enc(enc); if ((flags&ONIGENC_CASE_ASCII_ONLY) && (enc==rb_utf8_encoding() || rb_enc_mbmaxlen(enc)==1) || (!(flags&ONIGENC_CASE_FOLD_TURKISH_AZERI) && ENC_CODERANGE(str)==ENC_CODERANGE_7BIT)) { char *s = RSTRING_PTR(str), *send = RSTRING_END(str); while (s < send) { unsigned int c = *(unsigned char*)s; if (rb_enc_isascii(c, enc) && 'A' <= c && c <= 'Z') { *s = 'a' + (c - 'A'); flags |= ONIGENC_CASE_MODIFIED; } s++; } } else if (flags&ONIGENC_CASE_ASCII_ONLY) rb_str_ascii_casemap(str, &flags, enc); else str_shared_replace(str, rb_str_casemap(str, &flags, enc)); if (ONIGENC_CASE_MODIFIED&flags) return str; return Qnil; }
Produces a version of str
with all non-printing characters replaced by \nnn
notation and all special characters escaped.
"hello \n ''".dump #=> "\"hello \\n ''\""
VALUE rb_str_dump(VALUE str) { int encidx = rb_enc_get_index(str); rb_encoding *enc = rb_enc_from_index(encidx); long len; const char *p, *pend; char *q, *qend; VALUE result; int u8 = (encidx == rb_utf8_encindex()); static const char nonascii_suffix[] = ".force_encoding(\"%s\")"; len = 2; /* "" */ if (!rb_enc_asciicompat(enc)) { len += strlen(nonascii_suffix) - rb_strlen_lit("%s"); len += strlen(enc->name); } p = RSTRING_PTR(str); pend = p + RSTRING_LEN(str); while (p < pend) { int clen; unsigned char c = *p++; switch (c) { case '"': case '\\': case '\n': case '\r': case '\t': case '\f': case '\013': case '\010': case '\007': case '\033': clen = 2; break; case '#': clen = IS_EVSTR(p, pend) ? 2 : 1; break; default: if (ISPRINT(c)) { clen = 1; } else { if (u8 && c > 0x7F) { /* \u notation */ int n = rb_enc_precise_mbclen(p-1, pend, enc); if (MBCLEN_CHARFOUND_P(n)) { unsigned int cc = rb_enc_mbc_to_codepoint(p-1, pend, enc); if (cc <= 0xFFFF) clen = 6; /* \uXXXX */ else if (cc <= 0xFFFFF) clen = 9; /* \u{XXXXX} */ else clen = 10; /* \u{XXXXXX} */ p += MBCLEN_CHARFOUND_LEN(n)-1; break; } } clen = 4; /* \xNN */ } break; } if (clen > LONG_MAX - len) { rb_raise(rb_eRuntimeError, "string size too big"); } len += clen; } result = rb_str_new_with_class(str, 0, len); p = RSTRING_PTR(str); pend = p + RSTRING_LEN(str); q = RSTRING_PTR(result); qend = q + len + 1; *q++ = '"'; while (p < pend) { unsigned char c = *p++; if (c == '"' || c == '\\') { *q++ = '\\'; *q++ = c; } else if (c == '#') { if (IS_EVSTR(p, pend)) *q++ = '\\'; *q++ = '#'; } else if (c == '\n') { *q++ = '\\'; *q++ = 'n'; } else if (c == '\r') { *q++ = '\\'; *q++ = 'r'; } else if (c == '\t') { *q++ = '\\'; *q++ = 't'; } else if (c == '\f') { *q++ = '\\'; *q++ = 'f'; } else if (c == '\013') { *q++ = '\\'; *q++ = 'v'; } else if (c == '\010') { *q++ = '\\'; *q++ = 'b'; } else if (c == '\007') { *q++ = '\\'; *q++ = 'a'; } else if (c == '\033') { *q++ = '\\'; *q++ = 'e'; } else if (ISPRINT(c)) { *q++ = c; } else { *q++ = '\\'; if (u8) { int n = rb_enc_precise_mbclen(p-1, pend, enc) - 1; if (MBCLEN_CHARFOUND_P(n)) { int cc = rb_enc_mbc_to_codepoint(p-1, pend, enc); p += n; if (cc <= 0xFFFF) snprintf(q, qend-q, "u%04X", cc); /* \uXXXX */ else snprintf(q, qend-q, "u{%X}", cc); /* \u{XXXXX} or \u{XXXXXX} */ q += strlen(q); continue; } } snprintf(q, qend-q, "x%02X", c); q += 3; } } *q++ = '"'; *q = '\0'; if (!rb_enc_asciicompat(enc)) { snprintf(q, qend-q, nonascii_suffix, enc->name); encidx = rb_ascii8bit_encindex(); } OBJ_INFECT_RAW(result, str); /* result from dump is ASCII */ rb_enc_associate_index(result, encidx); ENC_CODERANGE_SET(result, ENC_CODERANGE_7BIT); return result; }
Passes each byte in str to the given block, or returns an enumerator if no block is given.
"hello".each_byte {|c| print c, ' ' }
produces:
104 101 108 108 111
static VALUE rb_str_each_byte(VALUE str) { return rb_str_enumerate_bytes(str, 0); }
Passes each character in str to the given block, or returns an enumerator if no block is given.
"hello".each_char {|c| print c, ' ' }
produces:
h e l l o
static VALUE rb_str_each_char(VALUE str) { return rb_str_enumerate_chars(str, 0); }
Passes the Integer
ordinal of each character in str, also known as a codepoint when applied to Unicode strings to the given block.
If no block is given, an enumerator is returned instead.
"hello\u0639".each_codepoint {|c| print c, ' ' }
produces:
104 101 108 108 111 1593
static VALUE rb_str_each_codepoint(VALUE str) { return rb_str_enumerate_codepoints(str, 0); }
Splits str using the supplied parameter as the record separator ($/
by default), passing each substring in turn to the supplied block. If a zero-length record separator is supplied, the string is split into paragraphs delimited by multiple successive newlines.
If no block is given, an enumerator is returned instead.
print "Example one\n" "hello\nworld".each_line {|s| p s} print "Example two\n" "hello\nworld".each_line('l') {|s| p s} print "Example three\n" "hello\n\n\nworld".each_line('') {|s| p s}
produces:
Example one "hello\n" "world" Example two "hel" "l" "o\nworl" "d" Example three "hello\n\n\n" "world"
static VALUE rb_str_each_line(int argc, VALUE *argv, VALUE str) { return rb_str_enumerate_lines(argc, argv, str, 0); }
Returns true
if str has a length of zero.
"hello".empty? #=> false " ".empty? #=> false "".empty? #=> true
static VALUE rb_str_empty(VALUE str) { if (RSTRING_LEN(str) == 0) return Qtrue; return Qfalse; }
The first form returns a copy of str
transcoded to encoding encoding
. The second form returns a copy of str
transcoded from src_encoding to dst_encoding. The last form returns a copy of str
transcoded to Encoding.default_internal
.
By default, the first and second form raise Encoding::UndefinedConversionError
for characters that are undefined in the destination encoding, and Encoding::InvalidByteSequenceError
for invalid byte sequences in the source encoding. The last form by default does not raise exceptions but uses replacement strings.
The options
Hash
gives details for conversion and can have the following keys:
If the value is :replace
, encode
replaces invalid byte sequences in str
with the replacement character. The default is to raise the Encoding::InvalidByteSequenceError
exception
If the value is :replace
, encode
replaces characters which are undefined in the destination encoding with the replacement character. The default is to raise the Encoding::UndefinedConversionError
.
Sets the replacement string to the given value. The default replacement string is “uFFFD” for Unicode encoding forms, and “?” otherwise.
Sets the replacement string by the given object for undefined character. The object should be a Hash
, a Proc
, a Method
, or an object which has [] method. Its key is an undefined character encoded in the source encoding of current transcoder. Its value can be any encoding until it can be converted into the destination encoding of the transcoder.
The value must be :text
or :attr
. If the value is :text
encode
replaces undefined characters with their (upper-case hexadecimal) numeric character references. '&', '<', and '>' are converted to “&”, “<”, and “>”, respectively. If the value is :attr
, encode
also quotes the replacement result (using '“'), and replaces '”' with “"”.
Replaces LF (“n”) with CR (“r”) if value is true.
Replaces LF (“n”) with CRLF (“rn”) if value is true.
Replaces CRLF (“rn”) and CR (“r”) with LF (“n”) if value is true.
static VALUE str_encode(int argc, VALUE *argv, VALUE str) { VALUE newstr = str; int encidx = str_transcode(argc, argv, &newstr); return encoded_dup(newstr, str, encidx); }
The first form transcodes the contents of str from str.encoding to encoding
. The second form transcodes the contents of str from src_encoding to dst_encoding. The options Hash
gives details for conversion. See String#encode
for details. Returns the string even if no changes were made.
static VALUE str_encode_bang(int argc, VALUE *argv, VALUE str) { VALUE newstr; int encidx; rb_check_frozen(str); newstr = str; encidx = str_transcode(argc, argv, &newstr); if (encidx < 0) return str; if (newstr == str) { rb_enc_associate_index(str, encidx); return str; } rb_str_shared_replace(str, newstr); return str_encode_associate(str, encidx); }
Returns the Encoding
object that represents the encoding of obj.
VALUE rb_obj_encoding(VALUE obj) { int idx = rb_enc_get_index(obj); if (idx < 0) { rb_raise(rb_eTypeError, "unknown encoding"); } return rb_enc_from_encoding_index(idx & ENC_INDEX_MASK); }
Returns true if str
ends with one of the suffixes
given.
"hello".end_with?("ello") #=> true # returns true if one of the +suffixes+ matches. "hello".end_with?("heaven", "ello") #=> true "hello".end_with?("heaven", "paradise") #=> false
static VALUE rb_str_end_with(int argc, VALUE *argv, VALUE str) { int i; char *p, *s, *e; rb_encoding *enc; for (i=0; i<argc; i++) { VALUE tmp = argv[i]; StringValue(tmp); enc = rb_enc_check(str, tmp); if (RSTRING_LEN(str) < RSTRING_LEN(tmp)) continue; p = RSTRING_PTR(str); e = p + RSTRING_LEN(str); s = e - RSTRING_LEN(tmp); if (rb_enc_left_char_head(p, s, e, enc) != s) continue; if (memcmp(s, RSTRING_PTR(tmp), RSTRING_LEN(tmp)) == 0) return Qtrue; } return Qfalse; }
Two strings are equal if they have the same length and content.
static VALUE rb_str_eql(VALUE str1, VALUE str2) { if (str1 == str2) return Qtrue; if (!RB_TYPE_P(str2, T_STRING)) return Qfalse; return str_eql(str1, str2); }
Changes the encoding to encoding
and returns self.
static VALUE rb_str_force_encoding(VALUE str, VALUE enc) { str_modifiable(str); rb_enc_associate(str, rb_to_encoding(enc)); ENC_CODERANGE_CLEAR(str); return str; }
VALUE rb_str_freeze(VALUE str) { if (OBJ_FROZEN(str)) return str; rb_str_resize(str, RSTRING_LEN(str)); return rb_obj_freeze(str); }
returns the indexth byte as an integer.
static VALUE rb_str_getbyte(VALUE str, VALUE index) { long pos = NUM2LONG(index); if (pos < 0) pos += RSTRING_LEN(str); if (pos < 0 || RSTRING_LEN(str) <= pos) return Qnil; return INT2FIX((unsigned char)RSTRING_PTR(str)[pos]); }
Returns a copy of str with the all occurrences of pattern substituted for the second argument. The pattern is typically a Regexp
; if given as a String
, any regular expression metacharacters it contains will be interpreted literally, e.g. '\\d'
will match a backslash followed by 'd', instead of a digit.
If replacement is a String
it will be substituted for the matched text. It may contain back-references to the pattern's capture groups of the form \\d
, where d is a group number, or \\k<n>
, where n is a group name. If it is a double-quoted string, both back-references must be preceded by an additional backslash. However, within replacement the special match variables, such as $&
, will not refer to the current match.
If the second argument is a Hash
, and the matched text is one of its keys, the corresponding value is the replacement string.
In the block form, the current match string is passed in as a parameter, and variables such as $1
, $2
, $`
, $&
, and $'
will be set appropriately. The value returned by the block will be substituted for the match on each call.
The result inherits any tainting in the original string or any supplied replacement string.
When neither a block nor a second argument is supplied, an Enumerator
is returned.
"hello".gsub(/[aeiou]/, '*') #=> "h*ll*" "hello".gsub(/([aeiou])/, '<\1>') #=> "h<e>ll<o>" "hello".gsub(/./) {|s| s.ord.to_s + ' '} #=> "104 101 108 108 111 " "hello".gsub(/(?<foo>[aeiou])/, '{\k<foo>}') #=> "h{e}ll{o}" 'hello'.gsub(/[eo]/, 'e' => 3, 'o' => '*') #=> "h3ll*"
static VALUE rb_str_gsub(int argc, VALUE *argv, VALUE str) { return str_gsub(argc, argv, str, 0); }
Performs the substitutions of String#gsub
in place, returning str, or nil
if no substitutions were performed. If no block and no replacement is given, an enumerator is returned instead.
static VALUE rb_str_gsub_bang(int argc, VALUE *argv, VALUE str) { str_modify_keep_cr(str); return str_gsub(argc, argv, str, 1); }
Return a hash based on the string's length, content and encoding.
See also Object#hash
.
static VALUE rb_str_hash_m(VALUE str) { st_index_t hval = rb_str_hash(str); return ST2FIX(hval); }
Treats leading characters from str as a string of hexadecimal digits (with an optional sign and an optional 0x
) and returns the corresponding number. Zero is returned on error.
"0x0a".hex #=> 10 "-1234".hex #=> -4660 "0".hex #=> 0 "wombat".hex #=> 0
static VALUE rb_str_hex(VALUE str) { return rb_str_to_inum(str, 16, FALSE); }
Returns true
if str contains the given string or character.
"hello".include? "lo" #=> true "hello".include? "ol" #=> false "hello".include? ?h #=> true
static VALUE rb_str_include(VALUE str, VALUE arg) { long i; StringValue(arg); i = rb_str_index(str, arg, 0); if (i == -1) return Qfalse; return Qtrue; }
Returns the index of the first occurrence of the given substring or pattern (regexp) in str. Returns nil
if not found. If the second parameter is present, it specifies the position in the string to begin the search.
"hello".index('e') #=> 1 "hello".index('lo') #=> 3 "hello".index('a') #=> nil "hello".index(?e) #=> 1 "hello".index(/[aeiou]/, -3) #=> 4
static VALUE rb_str_index_m(int argc, VALUE *argv, VALUE str) { VALUE sub; VALUE initpos; long pos; if (rb_scan_args(argc, argv, "11", &sub, &initpos) == 2) { pos = NUM2LONG(initpos); } else { pos = 0; } if (pos < 0) { pos += str_strlen(str, NULL); if (pos < 0) { if (RB_TYPE_P(sub, T_REGEXP)) { rb_backref_set(Qnil); } return Qnil; } } if (SPECIAL_CONST_P(sub)) goto generic; switch (BUILTIN_TYPE(sub)) { case T_REGEXP: if (pos > str_strlen(str, NULL)) return Qnil; pos = str_offset(RSTRING_PTR(str), RSTRING_END(str), pos, rb_enc_check(str, sub), single_byte_optimizable(str)); pos = rb_reg_search(sub, str, pos, 0); pos = rb_str_sublen(str, pos); break; generic: default: { VALUE tmp; tmp = rb_check_string_type(sub); if (NIL_P(tmp)) { rb_raise(rb_eTypeError, "type mismatch: %s given", rb_obj_classname(sub)); } sub = tmp; } /* fall through */ case T_STRING: pos = rb_str_index(str, sub, pos); pos = rb_str_sublen(str, pos); break; } if (pos == -1) return Qnil; return LONG2NUM(pos); }
Replaces the contents and taintedness of str with the corresponding values in other_str.
s = "hello" #=> "hello" s.replace "world" #=> "world"
VALUE rb_str_replace(VALUE str, VALUE str2) { str_modifiable(str); if (str == str2) return str; StringValue(str2); str_discard(str); return str_replace(str, str2); }
Inserts other_str before the character at the given index, modifying str. Negative indices count from the end of the string, and insert after the given character. The intent is insert aString so that it starts at the given index.
"abcd".insert(0, 'X') #=> "Xabcd" "abcd".insert(3, 'X') #=> "abcXd" "abcd".insert(4, 'X') #=> "abcdX" "abcd".insert(-3, 'X') #=> "abXcd" "abcd".insert(-1, 'X') #=> "abcdX"
static VALUE rb_str_insert(VALUE str, VALUE idx, VALUE str2) { long pos = NUM2LONG(idx); if (pos == -1) { return rb_str_append(str, str2); } else if (pos < 0) { pos++; } rb_str_splice(str, pos, 0, str2); return str; }
Returns a printable version of str, surrounded by quote marks, with special characters escaped.
str = "hello" str[3] = "\b" str.inspect #=> "\"hel\\bo\""
VALUE rb_str_inspect(VALUE str) { int encidx = ENCODING_GET(str); rb_encoding *enc = rb_enc_from_index(encidx), *actenc; const char *p, *pend, *prev; char buf[CHAR_ESC_LEN + 1]; VALUE result = rb_str_buf_new(0); rb_encoding *resenc = rb_default_internal_encoding(); int unicode_p = rb_enc_unicode_p(enc); int asciicompat = rb_enc_asciicompat(enc); if (resenc == NULL) resenc = rb_default_external_encoding(); if (!rb_enc_asciicompat(resenc)) resenc = rb_usascii_encoding(); rb_enc_associate(result, resenc); str_buf_cat2(result, "\""); p = RSTRING_PTR(str); pend = RSTRING_END(str); prev = p; actenc = get_actual_encoding(encidx, str); if (actenc != enc) { enc = actenc; if (unicode_p) unicode_p = rb_enc_unicode_p(enc); } while (p < pend) { unsigned int c, cc; int n; n = rb_enc_precise_mbclen(p, pend, enc); if (!MBCLEN_CHARFOUND_P(n)) { if (p > prev) str_buf_cat(result, prev, p - prev); n = rb_enc_mbminlen(enc); if (pend < p + n) n = (int)(pend - p); while (n--) { snprintf(buf, CHAR_ESC_LEN, "\\x%02X", *p & 0377); str_buf_cat(result, buf, strlen(buf)); prev = ++p; } continue; } n = MBCLEN_CHARFOUND_LEN(n); c = rb_enc_mbc_to_codepoint(p, pend, enc); p += n; if ((asciicompat || unicode_p) && (c == '"'|| c == '\\' || (c == '#' && p < pend && MBCLEN_CHARFOUND_P(rb_enc_precise_mbclen(p,pend,enc)) && (cc = rb_enc_codepoint(p,pend,enc), (cc == '$' || cc == '@' || cc == '{'))))) { if (p - n > prev) str_buf_cat(result, prev, p - n - prev); str_buf_cat2(result, "\\"); if (asciicompat || enc == resenc) { prev = p - n; continue; } } switch (c) { case '\n': cc = 'n'; break; case '\r': cc = 'r'; break; case '\t': cc = 't'; break; case '\f': cc = 'f'; break; case '\013': cc = 'v'; break; case '\010': cc = 'b'; break; case '\007': cc = 'a'; break; case 033: cc = 'e'; break; default: cc = 0; break; } if (cc) { if (p - n > prev) str_buf_cat(result, prev, p - n - prev); buf[0] = '\\'; buf[1] = (char)cc; str_buf_cat(result, buf, 2); prev = p; continue; } if ((enc == resenc && rb_enc_isprint(c, enc)) || (asciicompat && rb_enc_isascii(c, enc) && ISPRINT(c))) { continue; } else { if (p - n > prev) str_buf_cat(result, prev, p - n - prev); rb_str_buf_cat_escaped_char(result, c, unicode_p); prev = p; continue; } } if (p > prev) str_buf_cat(result, prev, p - prev); str_buf_cat2(result, "\""); OBJ_INFECT_RAW(result, str); return result; }
Returns the Symbol
corresponding to str, creating the symbol if it did not previously exist. See Symbol#id2name
.
"Koala".intern #=> :Koala s = 'cat'.to_sym #=> :cat s == :cat #=> true s = '@cat'.to_sym #=> :@cat s == :@cat #=> true
This can also be used to create symbols that cannot be represented using the :xxx
notation.
'cat and dog'.to_sym #=> :"cat and dog"
VALUE rb_str_intern(VALUE str) { #if USE_SYMBOL_GC rb_encoding *enc, *ascii; int type; #else ID id; #endif VALUE sym = lookup_str_sym(str); if (sym) { return sym; } #if USE_SYMBOL_GC enc = rb_enc_get(str); ascii = rb_usascii_encoding(); if (enc != ascii && sym_check_asciionly(str)) { str = rb_str_dup(str); rb_enc_associate(str, ascii); OBJ_FREEZE(str); enc = ascii; } else { str = rb_str_new_frozen(str); } str = rb_fstring(str); type = rb_str_symname_type(str, IDSET_ATTRSET_FOR_INTERN); if (type < 0) type = ID_JUNK; return dsymbol_alloc(rb_cSymbol, str, enc, type); #else id = intern_str(str, 0); return ID2SYM(id); #endif }
Returns the character length of str.
VALUE rb_str_length(VALUE str) { return LONG2NUM(str_strlen(str, NULL)); }
Returns an array of lines in str split using the supplied record separator ($/
by default). This is a shorthand for str.each_line(separator).to_a
.
If a block is given, which is a deprecated form, works the same as each_line
.
static VALUE rb_str_lines(int argc, VALUE *argv, VALUE str) { return rb_str_enumerate_lines(argc, argv, str, 1); }
If integer is greater than the length of str, returns a new String
of length integer with str left justified and padded with padstr; otherwise, returns str.
"hello".ljust(4) #=> "hello" "hello".ljust(20) #=> "hello " "hello".ljust(20, '1234') #=> "hello123412341234123"
static VALUE rb_str_ljust(int argc, VALUE *argv, VALUE str) { return rb_str_justify(argc, argv, str, 'l'); }
Returns a copy of str with leading whitespace removed. See also String#rstrip
and String#strip
.
Refer to strip
for the definition of whitespace.
" hello ".lstrip #=> "hello " "hello".lstrip #=> "hello"
static VALUE rb_str_lstrip(VALUE str) { char *start; long len, loffset; RSTRING_GETMEM(str, start, len); loffset = lstrip_offset(str, start, start+len, STR_ENC_GET(str)); if (loffset <= 0) return rb_str_dup(str); return rb_str_subseq(str, loffset, len - loffset); }
Removes leading whitespace from str, returning nil
if no change was made. See also String#rstrip!
and String#strip!
.
Refer to strip
for the definition of whitespace.
" hello ".lstrip! #=> "hello " "hello ".lstrip! #=> nil "hello".lstrip! #=> nil
static VALUE rb_str_lstrip_bang(VALUE str) { rb_encoding *enc; char *start, *s; long olen, loffset; str_modify_keep_cr(str); enc = STR_ENC_GET(str); RSTRING_GETMEM(str, start, olen); loffset = lstrip_offset(str, start, start+olen, enc); if (loffset > 0) { long len = olen-loffset; s = start + loffset; memmove(start, s, len); STR_SET_LEN(str, len); #if !SHARABLE_MIDDLE_SUBSTRING TERM_FILL(start+len, rb_enc_mbminlen(enc)); #endif return str; } return Qnil; }
Converts pattern to a Regexp
(if it isn't already one), then invokes its match
method on str. If the second parameter is present, it specifies the position in the string to begin the search.
'hello'.match('(.)\1') #=> #<MatchData "ll" 1:"l"> 'hello'.match('(.)\1')[0] #=> "ll" 'hello'.match(/(.)\1/)[0] #=> "ll" 'hello'.match('xx') #=> nil
If a block is given, invoke the block with MatchData
if match succeed, so that you can write
str.match(pat) {|m| ...}
instead of
if m = str.match(pat) ... end
The return value is a value from block execution in this case.
static VALUE rb_str_match_m(int argc, VALUE *argv, VALUE str) { VALUE re, result; if (argc < 1) rb_check_arity(argc, 1, 2); re = argv[0]; argv[0] = str; result = rb_funcallv(get_pat(re), rb_intern("match"), argc, argv); if (!NIL_P(result) && rb_block_given_p()) { return rb_yield(result); } return result; }
Converts pattern to a Regexp
(if it isn't already one), then returns a true
or false
indicates whether the regexp is matched str or not without updating $~
and other related variables. If the second parameter is present, it specifies the position in the string to begin the search.
"Ruby".match?(/R.../) #=> true "Ruby".match?(/R.../, 1) #=> false "Ruby".match?(/P.../) #=> false $& #=> nil
static VALUE rb_str_match_m_p(int argc, VALUE *argv, VALUE str) { VALUE re; rb_check_arity(argc, 1, 2); re = get_pat(argv[0]); return rb_reg_match_p(re, str, argc > 1 ? NUM2LONG(argv[1]) : 0); }
Returns the successor to str. The successor is calculated by incrementing characters starting from the rightmost alphanumeric (or the rightmost character if there are no alphanumerics) in the string. Incrementing a digit always results in another digit, and incrementing a letter results in another letter of the same case. Incrementing nonalphanumerics uses the underlying character set's collating sequence.
If the increment generates a “carry,'' the character to the left of it is incremented. This process repeats until there is no carry, adding an additional character if necessary.
"abcd".succ #=> "abce" "THX1138".succ #=> "THX1139" "<<koala>>".succ #=> "<<koalb>>" "1999zzz".succ #=> "2000aaa" "ZZZ9999".succ #=> "AAAA0000" "***".succ #=> "**+"
VALUE rb_str_succ(VALUE orig) { VALUE str; str = rb_str_new_with_class(orig, RSTRING_PTR(orig), RSTRING_LEN(orig)); rb_enc_cr_str_copy_for_substr(str, orig); OBJ_INFECT(str, orig); return str_succ(str); }
Equivalent to String#succ
, but modifies the receiver in place.
static VALUE rb_str_succ_bang(VALUE str) { rb_str_modify(str); str_succ(str); return str; }
Treats leading characters of str as a string of octal digits (with an optional sign) and returns the corresponding number. Returns 0 if the conversion fails.
"123".oct #=> 83 "-377".oct #=> -255 "bad".oct #=> 0 "0377bad".oct #=> 255
If str
starts with 0
, radix indicators are honored. See Kernel#Integer.
static VALUE rb_str_oct(VALUE str) { return rb_str_to_inum(str, -8, FALSE); }
Return the Integer
ordinal of a one-character string.
"a".ord #=> 97
VALUE rb_str_ord(VALUE s) { unsigned int c; c = rb_enc_codepoint(RSTRING_PTR(s), RSTRING_END(s), STR_ENC_GET(s)); return UINT2NUM(c); }
Searches sep or pattern (regexp) in the string and returns the part before it, the match, and the part after it. If it is not found, returns two empty strings and str.
"hello".partition("l") #=> ["he", "l", "lo"] "hello".partition("x") #=> ["hello", "", ""] "hello".partition(/.l/) #=> ["h", "el", "lo"]
static VALUE rb_str_partition(VALUE str, VALUE sep) { long pos; sep = get_pat_quoted(sep, 0); if (RB_TYPE_P(sep, T_REGEXP)) { pos = rb_reg_search(sep, str, 0, 0); if (pos < 0) { failed: return rb_ary_new3(3, str, str_new_empty(str), str_new_empty(str)); } sep = rb_str_subpat(str, sep, INT2FIX(0)); if (pos == 0 && RSTRING_LEN(sep) == 0) goto failed; } else { pos = rb_str_index(str, sep, 0); if (pos < 0) goto failed; } return rb_ary_new3(3, rb_str_subseq(str, 0, pos), sep, rb_str_subseq(str, pos+RSTRING_LEN(sep), RSTRING_LEN(str)-pos-RSTRING_LEN(sep))); }
Prepend—Prepend the given strings to str.
a = "!" a.prepend("hello ", "world") #=> "hello world!" a #=> "hello world!"
See also String#concat
.
static VALUE rb_str_prepend_multi(int argc, VALUE *argv, VALUE str) { str_modifiable(str); if (argc > 0) { int i; VALUE arg_str = rb_str_tmp_new(0); rb_enc_copy(arg_str, str); for (i = 0; i < argc; i++) { rb_str_append(arg_str, argv[i]); } rb_str_update(str, 0L, 0L, arg_str); } return str; }
Replaces the contents and taintedness of str with the corresponding values in other_str.
s = "hello" #=> "hello" s.replace "world" #=> "world"
VALUE rb_str_replace(VALUE str, VALUE str2) { str_modifiable(str); if (str == str2) return str; StringValue(str2); str_discard(str); return str_replace(str, str2); }
Returns a new string with the characters from str in reverse order.
"stressed".reverse #=> "desserts"
static VALUE rb_str_reverse(VALUE str) { rb_encoding *enc; VALUE rev; char *s, *e, *p; int cr; if (RSTRING_LEN(str) <= 1) return rb_str_dup(str); enc = STR_ENC_GET(str); rev = rb_str_new_with_class(str, 0, RSTRING_LEN(str)); s = RSTRING_PTR(str); e = RSTRING_END(str); p = RSTRING_END(rev); cr = ENC_CODERANGE(str); if (RSTRING_LEN(str) > 1) { if (single_byte_optimizable(str)) { while (s < e) { *--p = *s++; } } else if (cr == ENC_CODERANGE_VALID) { while (s < e) { int clen = rb_enc_fast_mbclen(s, e, enc); p -= clen; memcpy(p, s, clen); s += clen; } } else { cr = rb_enc_asciicompat(enc) ? ENC_CODERANGE_7BIT : ENC_CODERANGE_VALID; while (s < e) { int clen = rb_enc_mbclen(s, e, enc); if (clen > 1 || (*s & 0x80)) cr = ENC_CODERANGE_UNKNOWN; p -= clen; memcpy(p, s, clen); s += clen; } } } STR_SET_LEN(rev, RSTRING_LEN(str)); OBJ_INFECT_RAW(rev, str); str_enc_copy(rev, str); ENC_CODERANGE_SET(rev, cr); return rev; }
Reverses str in place.
static VALUE rb_str_reverse_bang(VALUE str) { if (RSTRING_LEN(str) > 1) { if (single_byte_optimizable(str)) { char *s, *e, c; str_modify_keep_cr(str); s = RSTRING_PTR(str); e = RSTRING_END(str) - 1; while (s < e) { c = *s; *s++ = *e; *e-- = c; } } else { str_shared_replace(str, rb_str_reverse(str)); } } else { str_modify_keep_cr(str); } return str; }
Returns the index of the last occurrence of the given substring or pattern (regexp) in str. Returns nil
if not found. If the second parameter is present, it specifies the position in the string to end the search—characters beyond this point will not be considered.
"hello".rindex('e') #=> 1 "hello".rindex('l') #=> 3 "hello".rindex('a') #=> nil "hello".rindex(?e) #=> 1 "hello".rindex(/[aeiou]/, -2) #=> 1
static VALUE rb_str_rindex_m(int argc, VALUE *argv, VALUE str) { VALUE sub; VALUE vpos; rb_encoding *enc = STR_ENC_GET(str); long pos, len = str_strlen(str, enc); /* str's enc */ if (rb_scan_args(argc, argv, "11", &sub, &vpos) == 2) { pos = NUM2LONG(vpos); if (pos < 0) { pos += len; if (pos < 0) { if (RB_TYPE_P(sub, T_REGEXP)) { rb_backref_set(Qnil); } return Qnil; } } if (pos > len) pos = len; } else { pos = len; } if (SPECIAL_CONST_P(sub)) goto generic; switch (BUILTIN_TYPE(sub)) { case T_REGEXP: /* enc = rb_get_check(str, sub); */ pos = str_offset(RSTRING_PTR(str), RSTRING_END(str), pos, enc, single_byte_optimizable(str)); pos = rb_reg_search(sub, str, pos, 1); pos = rb_str_sublen(str, pos); if (pos >= 0) return LONG2NUM(pos); break; generic: default: { VALUE tmp; tmp = rb_check_string_type(sub); if (NIL_P(tmp)) { rb_raise(rb_eTypeError, "type mismatch: %s given", rb_obj_classname(sub)); } sub = tmp; } /* fall through */ case T_STRING: pos = rb_str_rindex(str, sub, pos); if (pos >= 0) return LONG2NUM(pos); break; } return Qnil; }
If integer is greater than the length of str, returns a new String
of length integer with str right justified and padded with padstr; otherwise, returns str.
"hello".rjust(4) #=> "hello" "hello".rjust(20) #=> " hello" "hello".rjust(20, '1234') #=> "123412341234123hello"
static VALUE rb_str_rjust(int argc, VALUE *argv, VALUE str) { return rb_str_justify(argc, argv, str, 'r'); }
Searches sep or pattern (regexp) in the string from the end of the string, and returns the part before it, the match, and the part after it. If it is not found, returns two empty strings and str.
"hello".rpartition("l") #=> ["hel", "l", "o"] "hello".rpartition("x") #=> ["", "", "hello"] "hello".rpartition(/.l/) #=> ["he", "ll", "o"]
static VALUE rb_str_rpartition(VALUE str, VALUE sep) { long pos = RSTRING_LEN(str); int regex = FALSE; if (RB_TYPE_P(sep, T_REGEXP)) { pos = rb_reg_search(sep, str, pos, 1); regex = TRUE; } else { VALUE tmp; tmp = rb_check_string_type(sep); if (NIL_P(tmp)) { rb_raise(rb_eTypeError, "type mismatch: %s given", rb_obj_classname(sep)); } sep = tmp; pos = rb_str_sublen(str, pos); pos = rb_str_rindex(str, sep, pos); } if (pos < 0) { return rb_ary_new3(3, str_new_empty(str), str_new_empty(str), str); } if (regex) { sep = rb_reg_nth_match(0, rb_backref_get()); } else { pos = rb_str_offset(str, pos); } return rb_ary_new3(3, rb_str_subseq(str, 0, pos), sep, rb_str_subseq(str, pos+RSTRING_LEN(sep), RSTRING_LEN(str)-pos-RSTRING_LEN(sep))); }
Returns a copy of str with trailing whitespace removed. See also String#lstrip
and String#strip
.
Refer to strip
for the definition of whitespace.
" hello ".rstrip #=> " hello" "hello".rstrip #=> "hello"
static VALUE rb_str_rstrip(VALUE str) { rb_encoding *enc; char *start; long olen, roffset; enc = STR_ENC_GET(str); RSTRING_GETMEM(str, start, olen); roffset = rstrip_offset(str, start, start+olen, enc); if (roffset <= 0) return rb_str_dup(str); return rb_str_subseq(str, 0, olen-roffset); }
Removes trailing whitespace from str, returning nil
if no change was made. See also String#lstrip!
and String#strip!
.
Refer to strip
for the definition of whitespace.
" hello ".rstrip! #=> " hello" " hello".rstrip! #=> nil "hello".rstrip! #=> nil
static VALUE rb_str_rstrip_bang(VALUE str) { rb_encoding *enc; char *start; long olen, roffset; str_modify_keep_cr(str); enc = STR_ENC_GET(str); RSTRING_GETMEM(str, start, olen); roffset = rstrip_offset(str, start, start+olen, enc); if (roffset > 0) { long len = olen - roffset; STR_SET_LEN(str, len); #if !SHARABLE_MIDDLE_SUBSTRING TERM_FILL(start+len, rb_enc_mbminlen(enc)); #endif return str; } return Qnil; }
Both forms iterate through str, matching the pattern (which may be a Regexp
or a String
). For each match, a result is generated and either added to the result array or passed to the block. If the pattern contains no groups, each individual result consists of the matched string, $&
. If the pattern contains groups, each individual result is itself an array containing one entry per group.
a = "cruel world" a.scan(/\w+/) #=> ["cruel", "world"] a.scan(/.../) #=> ["cru", "el ", "wor"] a.scan(/(...)/) #=> [["cru"], ["el "], ["wor"]] a.scan(/(..)(..)/) #=> [["cr", "ue"], ["l ", "wo"]]
And the block form:
a.scan(/\w+/) {|w| print "<<#{w}>> " } print "\n" a.scan(/(.)(.)/) {|x,y| print y, x } print "\n"
produces:
<<cruel>> <<world>> rceu lowlr
static VALUE rb_str_scan(VALUE str, VALUE pat) { VALUE result; long start = 0; long last = -1, prev = 0; char *p = RSTRING_PTR(str); long len = RSTRING_LEN(str); pat = get_pat_quoted(pat, 1); mustnot_broken(str); if (!rb_block_given_p()) { VALUE ary = rb_ary_new(); while (!NIL_P(result = scan_once(str, pat, &start))) { last = prev; prev = start; rb_ary_push(ary, result); } if (last >= 0) rb_pat_search(pat, str, last, 1); return ary; } while (!NIL_P(result = scan_once(str, pat, &start))) { last = prev; prev = start; rb_yield(result); str_mod_check(str, p, len); } if (last >= 0) rb_pat_search(pat, str, last, 1); return str; }
If the string is invalid byte sequence then replace invalid bytes with given replacement character, else returns self. If block is given, replace invalid bytes with returned value of the block.
"abc\u3042\x81".scrub #=> "abc\u3042\uFFFD" "abc\u3042\x81".scrub("*") #=> "abc\u3042*" "abc\u3042\xE3\x80".scrub{|bytes| '<'+bytes.unpack('H*')[0]+'>' } #=> "abc\u3042<e380>"
static VALUE str_scrub(int argc, VALUE *argv, VALUE str) { VALUE repl = argc ? (rb_check_arity(argc, 0, 1), argv[0]) : Qnil; VALUE new = rb_str_scrub(str, repl); return NIL_P(new) ? rb_str_dup(str): new; }
If the string is invalid byte sequence then replace invalid bytes with given replacement character, else returns self. If block is given, replace invalid bytes with returned value of the block.
"abc\u3042\x81".scrub! #=> "abc\u3042\uFFFD" "abc\u3042\x81".scrub!("*") #=> "abc\u3042*" "abc\u3042\xE3\x80".scrub!{|bytes| '<'+bytes.unpack('H*')[0]+'>' } #=> "abc\u3042<e380>"
static VALUE str_scrub_bang(int argc, VALUE *argv, VALUE str) { VALUE repl = argc ? (rb_check_arity(argc, 0, 1), argv[0]) : Qnil; VALUE new = rb_str_scrub(str, repl); if (!NIL_P(new)) rb_str_replace(str, new); return str; }
modifies the indexth byte as integer.
static VALUE rb_str_setbyte(VALUE str, VALUE index, VALUE value) { long pos = NUM2LONG(index); int byte = NUM2INT(value); long len = RSTRING_LEN(str); char *head, *ptr, *left = 0; rb_encoding *enc; int cr = ENC_CODERANGE_UNKNOWN, width, nlen; if (pos < -len || len <= pos) rb_raise(rb_eIndexError, "index %ld out of string", pos); if (pos < 0) pos += len; if (!str_independent(str)) str_make_independent(str); enc = STR_ENC_GET(str); head = RSTRING_PTR(str); ptr = &head[pos]; if (!STR_EMBEDDABLE_P(len, rb_enc_mbminlen(enc))) { cr = ENC_CODERANGE(str); switch (cr) { case ENC_CODERANGE_7BIT: left = ptr; *ptr = byte; if (ISASCII(byte)) break; nlen = rb_enc_precise_mbclen(left, head+len, enc); if (!MBCLEN_CHARFOUND_P(nlen)) ENC_CODERANGE_SET(str, ENC_CODERANGE_BROKEN); else ENC_CODERANGE_SET(str, ENC_CODERANGE_VALID); goto end; case ENC_CODERANGE_VALID: left = rb_enc_left_char_head(head, ptr, head+len, enc); width = rb_enc_precise_mbclen(left, head+len, enc); *ptr = byte; nlen = rb_enc_precise_mbclen(left, head+len, enc); if (!MBCLEN_CHARFOUND_P(nlen)) ENC_CODERANGE_SET(str, ENC_CODERANGE_BROKEN); else if (MBCLEN_CHARFOUND_LEN(nlen) != width || ISASCII(byte)) ENC_CODERANGE_CLEAR(str); goto end; } } ENC_CODERANGE_CLEAR(str); *ptr = byte; end: return value; }
Returns the character length of str.
VALUE rb_str_length(VALUE str) { return LONG2NUM(str_strlen(str, NULL)); }
Element Reference — If passed a single index
, returns a substring of one character at that index. If passed a start
index and a length
, returns a substring containing length
characters starting at the start
index. If passed a range
, its beginning and end are interpreted as offsets delimiting the substring to be returned.
In these three cases, if an index is negative, it is counted from the end of the string. For the start
and range
cases the starting index is just before a character and an index matching the string's size. Additionally, an empty string is returned when the starting index for a character range is at the end of the string.
Returns nil
if the initial index falls outside the string or the length is negative.
If a Regexp
is supplied, the matching portion of the string is returned. If a capture
follows the regular expression, which may be a capture group index or name, follows the regular expression that component of the MatchData
is returned instead.
If a match_str
is given, that string is returned if it occurs in the string.
Returns nil
if the regular expression does not match or the match string cannot be found.
a = "hello there" a[1] #=> "e" a[2, 3] #=> "llo" a[2..3] #=> "ll" a[-3, 2] #=> "er" a[7..-2] #=> "her" a[-4..-2] #=> "her" a[-2..-4] #=> "" a[11, 0] #=> "" a[11] #=> nil a[12, 0] #=> nil a[12..-1] #=> nil a[/[aeiou](.)\1/] #=> "ell" a[/[aeiou](.)\1/, 0] #=> "ell" a[/[aeiou](.)\1/, 1] #=> "l" a[/[aeiou](.)\1/, 2] #=> nil a[/(?<vowel>[aeiou])(?<non_vowel>[^aeiou])/, "non_vowel"] #=> "l" a[/(?<vowel>[aeiou])(?<non_vowel>[^aeiou])/, "vowel"] #=> "e" a["lo"] #=> "lo" a["bye"] #=> nil
static VALUE rb_str_aref_m(int argc, VALUE *argv, VALUE str) { if (argc == 2) { if (RB_TYPE_P(argv[0], T_REGEXP)) { return rb_str_subpat(str, argv[0], argv[1]); } else { long beg = NUM2LONG(argv[0]); long len = NUM2LONG(argv[1]); return rb_str_substr(str, beg, len); } } rb_check_arity(argc, 1, 2); return rb_str_aref(str, argv[0]); }
Deletes the specified portion from str, and returns the portion deleted.
string = "this is a string" string.slice!(2) #=> "i" string.slice!(3..6) #=> " is " string.slice!(/s.*t/) #=> "sa st" string.slice!("r") #=> "r" string #=> "thing"
static VALUE rb_str_slice_bang(int argc, VALUE *argv, VALUE str) { VALUE result; VALUE buf[3]; int i; rb_check_arity(argc, 1, 2); for (i=0; i<argc; i++) { buf[i] = argv[i]; } str_modify_keep_cr(str); result = rb_str_aref_m(argc, buf, str); if (!NIL_P(result)) { buf[i] = rb_str_new(0,0); rb_str_aset_m(argc+1, buf, str); } return result; }
Divides str into substrings based on a delimiter, returning an array of these substrings.
If pattern is a String
, then its contents are used as the delimiter when splitting str. If pattern is a single space, str is split on whitespace, with leading whitespace and runs of contiguous whitespace characters ignored.
If pattern is a Regexp
, str is divided where the pattern matches. Whenever the pattern matches a zero-length string, str is split into individual characters. If pattern contains groups, the respective matches will be returned in the array as well.
If pattern is nil
, the value of $;
is used. If $;
is nil
(which is the default), str is split on whitespace as if ' ' were specified.
If the limit parameter is omitted, trailing null fields are suppressed. If limit is a positive number, at most that number of fields will be returned (if limit is 1
, the entire string is returned as the only entry in an array). If negative, there is no limit to the number of fields returned, and trailing null fields are not suppressed.
When the input str
is empty an empty Array
is returned as the string is considered to have no fields to split.
" now's the time".split #=> ["now's", "the", "time"] " now's the time".split(' ') #=> ["now's", "the", "time"] " now's the time".split(/ /) #=> ["", "now's", "", "the", "time"] "1, 2.34,56, 7".split(%r{,\s*}) #=> ["1", "2.34", "56", "7"] "hello".split(//) #=> ["h", "e", "l", "l", "o"] "hello".split(//, 3) #=> ["h", "e", "llo"] "hi mom".split(%r{\s*}) #=> ["h", "i", "m", "o", "m"] "mellow yellow".split("ello") #=> ["m", "w y", "w"] "1,2,,3,4,,".split(',') #=> ["1", "2", "", "3", "4"] "1,2,,3,4,,".split(',', 4) #=> ["1", "2", "", "3,4,,"] "1,2,,3,4,,".split(',', -4) #=> ["1", "2", "", "3", "4", "", ""] "".split(',', -1) #=> []
static VALUE rb_str_split_m(int argc, VALUE *argv, VALUE str) { rb_encoding *enc; VALUE spat; VALUE limit; enum {awk, string, regexp} split_type; long beg, end, i = 0; int lim = 0; VALUE result, tmp; if (rb_scan_args(argc, argv, "02", &spat, &limit) == 2) { lim = NUM2INT(limit); if (lim <= 0) limit = Qnil; else if (lim == 1) { if (RSTRING_LEN(str) == 0) return rb_ary_new2(0); return rb_ary_new3(1, str); } i = 1; } enc = STR_ENC_GET(str); split_type = regexp; if (!NIL_P(spat)) { spat = get_pat_quoted(spat, 0); } else if (NIL_P(spat = rb_fs)) { split_type = awk; } else if (!(spat = rb_fs_check(spat))) { rb_raise(rb_eTypeError, "value of $; must be String or Regexp"); } if (split_type != awk) { if (BUILTIN_TYPE(spat) == T_STRING) { rb_encoding *enc2 = STR_ENC_GET(spat); mustnot_broken(spat); split_type = string; if (RSTRING_LEN(spat) == 0) { /* Special case - split into chars */ spat = rb_reg_regcomp(spat); split_type = regexp; } else if (rb_enc_asciicompat(enc2) == 1) { if (RSTRING_LEN(spat) == 1 && RSTRING_PTR(spat)[0] == ' ') { split_type = awk; } } else { int l; if (rb_enc_ascget(RSTRING_PTR(spat), RSTRING_END(spat), &l, enc2) == ' ' && RSTRING_LEN(spat) == l) { split_type = awk; } } } } result = rb_ary_new(); beg = 0; if (split_type == awk) { char *ptr = RSTRING_PTR(str); char *eptr = RSTRING_END(str); char *bptr = ptr; int skip = 1; unsigned int c; end = beg; if (is_ascii_string(str)) { while (ptr < eptr) { c = (unsigned char)*ptr++; if (skip) { if (ascii_isspace(c)) { beg = ptr - bptr; } else { end = ptr - bptr; skip = 0; if (!NIL_P(limit) && lim <= i) break; } } else if (ascii_isspace(c)) { rb_ary_push(result, rb_str_subseq(str, beg, end-beg)); skip = 1; beg = ptr - bptr; if (!NIL_P(limit)) ++i; } else { end = ptr - bptr; } } } else { while (ptr < eptr) { int n; c = rb_enc_codepoint_len(ptr, eptr, &n, enc); ptr += n; if (skip) { if (rb_isspace(c)) { beg = ptr - bptr; } else { end = ptr - bptr; skip = 0; if (!NIL_P(limit) && lim <= i) break; } } else if (rb_isspace(c)) { rb_ary_push(result, rb_str_subseq(str, beg, end-beg)); skip = 1; beg = ptr - bptr; if (!NIL_P(limit)) ++i; } else { end = ptr - bptr; } } } } else if (split_type == string) { char *ptr = RSTRING_PTR(str); char *temp = ptr; char *eptr = RSTRING_END(str); char *sptr = RSTRING_PTR(spat); long slen = RSTRING_LEN(spat); mustnot_broken(str); enc = rb_enc_check(str, spat); while (ptr < eptr && (end = rb_memsearch(sptr, slen, ptr, eptr - ptr, enc)) >= 0) { /* Check we are at the start of a char */ char *t = rb_enc_right_char_head(ptr, ptr + end, eptr, enc); if (t != ptr + end) { ptr = t; continue; } rb_ary_push(result, rb_str_subseq(str, ptr - temp, end)); ptr += end + slen; if (!NIL_P(limit) && lim <= ++i) break; } beg = ptr - temp; } else { char *ptr = RSTRING_PTR(str); long len = RSTRING_LEN(str); long start = beg; long idx; int last_null = 0; struct re_registers *regs; while ((end = rb_reg_search(spat, str, start, 0)) >= 0) { regs = RMATCH_REGS(rb_backref_get()); if (start == end && BEG(0) == END(0)) { if (!ptr) { rb_ary_push(result, str_new_empty(str)); break; } else if (last_null == 1) { rb_ary_push(result, rb_str_subseq(str, beg, rb_enc_fast_mbclen(ptr+beg, ptr+len, enc))); beg = start; } else { if (start == len) start++; else start += rb_enc_fast_mbclen(ptr+start,ptr+len,enc); last_null = 1; continue; } } else { rb_ary_push(result, rb_str_subseq(str, beg, end-beg)); beg = start = END(0); } last_null = 0; for (idx=1; idx < regs->num_regs; idx++) { if (BEG(idx) == -1) continue; if (BEG(idx) == END(idx)) tmp = str_new_empty(str); else tmp = rb_str_subseq(str, BEG(idx), END(idx)-BEG(idx)); rb_ary_push(result, tmp); } if (!NIL_P(limit) && lim <= ++i) break; } } if (RSTRING_LEN(str) > 0 && (!NIL_P(limit) || RSTRING_LEN(str) > beg || lim < 0)) { if (RSTRING_LEN(str) == beg) tmp = str_new_empty(str); else tmp = rb_str_subseq(str, beg, RSTRING_LEN(str)-beg); rb_ary_push(result, tmp); } if (NIL_P(limit) && lim == 0) { long len; while ((len = RARRAY_LEN(result)) > 0 && (tmp = RARRAY_AREF(result, len-1), RSTRING_LEN(tmp) == 0)) rb_ary_pop(result); } return result; }
Builds a set of characters from the other_str parameter(s) using the procedure described for String#count
. Returns a new string where runs of the same character that occur in this set are replaced by a single character. If no arguments are given, all runs of identical characters are replaced by a single character.
"yellow moon".squeeze #=> "yelow mon" " now is the".squeeze(" ") #=> " now is the" "putters shoot balls".squeeze("m-z") #=> "puters shot balls"
static VALUE rb_str_squeeze(int argc, VALUE *argv, VALUE str) { str = rb_str_dup(str); rb_str_squeeze_bang(argc, argv, str); return str; }
Squeezes str in place, returning either str, or nil
if no changes were made.
static VALUE rb_str_squeeze_bang(int argc, VALUE *argv, VALUE str) { char squeez[TR_TABLE_SIZE]; rb_encoding *enc = 0; VALUE del = 0, nodel = 0; char *s, *send, *t; int i, modify = 0; int ascompat, singlebyte = single_byte_optimizable(str); unsigned int save; if (argc == 0) { enc = STR_ENC_GET(str); } else { for (i=0; i<argc; i++) { VALUE s = argv[i]; StringValue(s); enc = rb_enc_check(str, s); if (singlebyte && !single_byte_optimizable(s)) singlebyte = 0; tr_setup_table(s, squeez, i==0, &del, &nodel, enc); } } str_modify_keep_cr(str); s = t = RSTRING_PTR(str); if (!s || RSTRING_LEN(str) == 0) return Qnil; send = RSTRING_END(str); save = -1; ascompat = rb_enc_asciicompat(enc); if (singlebyte) { while (s < send) { unsigned int c = *(unsigned char*)s++; if (c != save || (argc > 0 && !squeez[c])) { *t++ = save = c; } } } else { while (s < send) { unsigned int c; int clen; if (ascompat && (c = *(unsigned char*)s) < 0x80) { if (c != save || (argc > 0 && !squeez[c])) { *t++ = save = c; } s++; } else { c = rb_enc_codepoint_len(s, send, &clen, enc); if (c != save || (argc > 0 && !tr_find(c, squeez, del, nodel))) { if (t != s) rb_enc_mbcput(c, t, enc); save = c; t += clen; } s += clen; } } } TERM_FILL(t, TERM_LEN(str)); if (t - RSTRING_PTR(str) != RSTRING_LEN(str)) { STR_SET_LEN(str, t - RSTRING_PTR(str)); modify = 1; } if (modify) return str; return Qnil; }
Returns true if str
starts with one of the prefixes
given.
"hello".start_with?("hell") #=> true # returns true if one of the prefixes matches. "hello".start_with?("heaven", "hell") #=> true "hello".start_with?("heaven", "paradise") #=> false
static VALUE rb_str_start_with(int argc, VALUE *argv, VALUE str) { int i; for (i=0; i<argc; i++) { VALUE tmp = argv[i]; StringValue(tmp); rb_enc_check(str, tmp); if (RSTRING_LEN(str) < RSTRING_LEN(tmp)) continue; if (memcmp(RSTRING_PTR(str), RSTRING_PTR(tmp), RSTRING_LEN(tmp)) == 0) return Qtrue; } return Qfalse; }
Returns a copy of str with leading and trailing whitespace removed.
Whitespace is defined as any of the following characters: null, horizontal tab, line feed, vertical tab, form feed, carriage return, space.
" hello ".strip #=> "hello" "\tgoodbye\r\n".strip #=> "goodbye" "\x00\t\n\v\f\r ".strip #=> ""
static VALUE rb_str_strip(VALUE str) { char *start; long olen, loffset, roffset; rb_encoding *enc = STR_ENC_GET(str); RSTRING_GETMEM(str, start, olen); loffset = lstrip_offset(str, start, start+olen, enc); roffset = rstrip_offset(str, start+loffset, start+olen, enc); if (loffset <= 0 && roffset <= 0) return rb_str_dup(str); return rb_str_subseq(str, loffset, olen-loffset-roffset); }
Removes leading and trailing whitespace from str. Returns nil
if str was not altered.
Refer to strip
for the definition of whitespace.
static VALUE rb_str_strip_bang(VALUE str) { char *start; long olen, loffset, roffset; rb_encoding *enc; str_modify_keep_cr(str); enc = STR_ENC_GET(str); RSTRING_GETMEM(str, start, olen); loffset = lstrip_offset(str, start, start+olen, enc); roffset = rstrip_offset(str, start+loffset, start+olen, enc); if (loffset > 0 || roffset > 0) { long len = olen-roffset; if (loffset > 0) { len -= loffset; memmove(start, start + loffset, len); } STR_SET_LEN(str, len); #if !SHARABLE_MIDDLE_SUBSTRING TERM_FILL(start+len, rb_enc_mbminlen(enc)); #endif return str; } return Qnil; }
Returns a copy of str
with the first occurrence of pattern
replaced by the second argument. The pattern
is typically a Regexp
; if given as a String
, any regular expression metacharacters it contains will be interpreted literally, e.g. '\\d'
will match a backslash followed by 'd', instead of a digit.
If replacement
is a String
it will be substituted for the matched text. It may contain back-references to the pattern's capture groups of the form "\d"
, where d is a group number, or "\k<n>"
, where n is a group name. If it is a double-quoted string, both back-references must be preceded by an additional backslash. However, within replacement
the special match variables, such as $&
, will not refer to the current match. If replacement
is a String
that looks like a pattern's capture group but is actually not a pattern capture group e.g. "\'"
, then it will have to be preceded by two backslashes like so "\\'"
.
If the second argument is a Hash
, and the matched text is one of its keys, the corresponding value is the replacement string.
In the block form, the current match string is passed in as a parameter, and variables such as $1
, $2
, $`
, $&
, and $'
will be set appropriately. The value returned by the block will be substituted for the match on each call.
The result inherits any tainting in the original string or any supplied replacement string.
"hello".sub(/[aeiou]/, '*') #=> "h*llo" "hello".sub(/([aeiou])/, '<\1>') #=> "h<e>llo" "hello".sub(/./) {|s| s.ord.to_s + ' ' } #=> "104 ello" "hello".sub(/(?<foo>[aeiou])/, '*\k<foo>*') #=> "h*e*llo" 'Is SHELL your preferred shell?'.sub(/[[:upper:]]{2,}/, ENV) #=> "Is /bin/bash your preferred shell?"
static VALUE rb_str_sub(int argc, VALUE *argv, VALUE str) { str = rb_str_dup(str); rb_str_sub_bang(argc, argv, str); return str; }
Performs the same substitution as String#sub
in-place.
Returns str
if a substitution was performed or nil
if no substitution was performed.
static VALUE rb_str_sub_bang(int argc, VALUE *argv, VALUE str) { VALUE pat, repl, hash = Qnil; int iter = 0; int tainted = 0; long plen; int min_arity = rb_block_given_p() ? 1 : 2; long beg; rb_check_arity(argc, min_arity, 2); if (argc == 1) { iter = 1; } else { repl = argv[1]; hash = rb_check_hash_type(argv[1]); if (NIL_P(hash)) { StringValue(repl); } tainted = OBJ_TAINTED_RAW(repl); } pat = get_pat_quoted(argv[0], 1); str_modifiable(str); beg = rb_pat_search(pat, str, 0, 1); if (beg >= 0) { rb_encoding *enc; int cr = ENC_CODERANGE(str); long beg0, end0; VALUE match, match0 = Qnil; struct re_registers *regs; char *p, *rp; long len, rlen; match = rb_backref_get(); regs = RMATCH_REGS(match); if (RB_TYPE_P(pat, T_STRING)) { beg0 = beg; end0 = beg0 + RSTRING_LEN(pat); match0 = pat; } else { beg0 = BEG(0); end0 = END(0); if (iter) match0 = rb_reg_nth_match(0, match); } if (iter || !NIL_P(hash)) { p = RSTRING_PTR(str); len = RSTRING_LEN(str); if (iter) { repl = rb_obj_as_string(rb_yield(match0)); } else { repl = rb_hash_aref(hash, rb_str_subseq(str, beg0, end0 - beg0)); repl = rb_obj_as_string(repl); } str_mod_check(str, p, len); rb_check_frozen(str); } else { repl = rb_reg_regsub(repl, str, regs, RB_TYPE_P(pat, T_STRING) ? Qnil : pat); } enc = rb_enc_compatible(str, repl); if (!enc) { rb_encoding *str_enc = STR_ENC_GET(str); p = RSTRING_PTR(str); len = RSTRING_LEN(str); if (coderange_scan(p, beg0, str_enc) != ENC_CODERANGE_7BIT || coderange_scan(p+end0, len-end0, str_enc) != ENC_CODERANGE_7BIT) { rb_raise(rb_eEncCompatError, "incompatible character encodings: %s and %s", rb_enc_name(str_enc), rb_enc_name(STR_ENC_GET(repl))); } enc = STR_ENC_GET(repl); } rb_str_modify(str); rb_enc_associate(str, enc); tainted |= OBJ_TAINTED_RAW(repl); if (ENC_CODERANGE_UNKNOWN < cr && cr < ENC_CODERANGE_BROKEN) { int cr2 = ENC_CODERANGE(repl); if (cr2 == ENC_CODERANGE_BROKEN || (cr == ENC_CODERANGE_VALID && cr2 == ENC_CODERANGE_7BIT)) cr = ENC_CODERANGE_UNKNOWN; else cr = cr2; } plen = end0 - beg0; rp = RSTRING_PTR(repl); rlen = RSTRING_LEN(repl); len = RSTRING_LEN(str); if (rlen > plen) { RESIZE_CAPA(str, len + rlen - plen); } p = RSTRING_PTR(str); if (rlen != plen) { memmove(p + beg0 + rlen, p + beg0 + plen, len - beg0 - plen); } memcpy(p + beg0, rp, rlen); len += rlen - plen; STR_SET_LEN(str, len); TERM_FILL(&RSTRING_PTR(str)[len], TERM_LEN(str)); ENC_CODERANGE_SET(str, cr); FL_SET_RAW(str, tainted); return str; } return Qnil; }
Returns the successor to str. The successor is calculated by incrementing characters starting from the rightmost alphanumeric (or the rightmost character if there are no alphanumerics) in the string. Incrementing a digit always results in another digit, and incrementing a letter results in another letter of the same case. Incrementing nonalphanumerics uses the underlying character set's collating sequence.
If the increment generates a “carry,'' the character to the left of it is incremented. This process repeats until there is no carry, adding an additional character if necessary.
"abcd".succ #=> "abce" "THX1138".succ #=> "THX1139" "<<koala>>".succ #=> "<<koalb>>" "1999zzz".succ #=> "2000aaa" "ZZZ9999".succ #=> "AAAA0000" "***".succ #=> "**+"
VALUE rb_str_succ(VALUE orig) { VALUE str; str = rb_str_new_with_class(orig, RSTRING_PTR(orig), RSTRING_LEN(orig)); rb_enc_cr_str_copy_for_substr(str, orig); OBJ_INFECT(str, orig); return str_succ(str); }
Equivalent to String#succ
, but modifies the receiver in place.
static VALUE rb_str_succ_bang(VALUE str) { rb_str_modify(str); str_succ(str); return str; }
Returns a basic n-bit checksum of the characters in str, where n is the optional Integer
parameter, defaulting to 16. The result is simply the sum of the binary value of each byte in str modulo 2**n - 1
. This is not a particularly good checksum.
static VALUE rb_str_sum(int argc, VALUE *argv, VALUE str) { VALUE vbits; int bits; char *ptr, *p, *pend; long len; VALUE sum = INT2FIX(0); unsigned long sum0 = 0; if (argc == 0) { bits = 16; } else { rb_scan_args(argc, argv, "01", &vbits); bits = NUM2INT(vbits); if (bits < 0) bits = 0; } ptr = p = RSTRING_PTR(str); len = RSTRING_LEN(str); pend = p + len; while (p < pend) { if (FIXNUM_MAX - UCHAR_MAX < sum0) { sum = rb_funcall(sum, '+', 1, LONG2FIX(sum0)); str_mod_check(str, ptr, len); sum0 = 0; } sum0 += (unsigned char)*p; p++; } if (bits == 0) { if (sum0) { sum = rb_funcall(sum, '+', 1, LONG2FIX(sum0)); } } else { if (sum == INT2FIX(0)) { if (bits < (int)sizeof(long)*CHAR_BIT) { sum0 &= (((unsigned long)1)<<bits)-1; } sum = LONG2FIX(sum0); } else { VALUE mod; if (sum0) { sum = rb_funcall(sum, '+', 1, LONG2FIX(sum0)); } mod = rb_funcall(INT2FIX(1), idLTLT, 1, INT2FIX(bits)); mod = rb_funcall(mod, '-', 1, INT2FIX(1)); sum = rb_funcall(sum, '&', 1, mod); } } return sum; }
Returns a copy of str with uppercase alphabetic characters converted to lowercase and lowercase characters converted to uppercase.
See String#downcase
for meaning of options
and use with different encodings.
"Hello".swapcase #=> "hELLO" "cYbEr_PuNk11".swapcase #=> "CyBeR_pUnK11"
static VALUE rb_str_swapcase(int argc, VALUE *argv, VALUE str) { str = rb_str_dup(str); rb_str_swapcase_bang(argc, argv, str); return str; }
Equivalent to String#swapcase
, but modifies the receiver in place, returning str, or nil
if no changes were made.
See String#downcase
for meaning of options
and use with different encodings.
static VALUE rb_str_swapcase_bang(int argc, VALUE *argv, VALUE str) { rb_encoding *enc; OnigCaseFoldType flags = ONIGENC_CASE_UPCASE | ONIGENC_CASE_DOWNCASE; flags = check_case_options(argc, argv, flags); str_modify_keep_cr(str); enc = STR_ENC_GET(str); rb_str_check_dummy_enc(enc); if (flags&ONIGENC_CASE_ASCII_ONLY) rb_str_ascii_casemap(str, &flags, enc); else str_shared_replace(str, rb_str_casemap(str, &flags, enc)); if (ONIGENC_CASE_MODIFIED&flags) return str; return Qnil; }
Returns a complex which denotes the string form. The parser ignores leading whitespaces and trailing garbage. Any digit sequences can be separated by an underscore. Returns zero for null or garbage string.
'9'.to_c #=> (9+0i) '2.5'.to_c #=> (2.5+0i) '2.5/1'.to_c #=> ((5/2)+0i) '-3/2'.to_c #=> ((-3/2)+0i) '-i'.to_c #=> (0-1i) '45i'.to_c #=> (0+45i) '3-4i'.to_c #=> (3-4i) '-4e2-4e-2i'.to_c #=> (-400.0-0.04i) '-0.0-0.0i'.to_c #=> (-0.0-0.0i) '1/2+3/4i'.to_c #=> ((1/2)+(3/4)*i) 'ruby'.to_c #=> (0+0i)
See Kernel
.Complex.
static VALUE string_to_c(VALUE self) { char *s; VALUE num; rb_must_asciicompat(self); s = RSTRING_PTR(self); if (s && s[RSTRING_LEN(self)]) { rb_str_modify(self); s = RSTRING_PTR(self); s[RSTRING_LEN(self)] = '\0'; } if (!s) s = (char *)""; (void)parse_comp(s, 0, &num); return num; }
Returns the result of interpreting leading characters in str as a floating point number. Extraneous characters past the end of a valid number are ignored. If there is not a valid number at the start of str, 0.0
is returned. This method never raises an exception.
"123.45e1".to_f #=> 1234.5 "45.67 degrees".to_f #=> 45.67 "thx1138".to_f #=> 0.0
static VALUE rb_str_to_f(VALUE str) { return DBL2NUM(rb_str_to_dbl(str, FALSE)); }
Returns the result of interpreting leading characters in str as an integer base base (between 2 and 36). Extraneous characters past the end of a valid number are ignored. If there is not a valid number at the start of str, 0
is returned. This method never raises an exception when base is valid.
"12345".to_i #=> 12345 "99 red balloons".to_i #=> 99 "0a".to_i #=> 0 "0a".to_i(16) #=> 10 "hello".to_i #=> 0 "1100101".to_i(2) #=> 101 "1100101".to_i(8) #=> 294977 "1100101".to_i(10) #=> 1100101 "1100101".to_i(16) #=> 17826049
static VALUE rb_str_to_i(int argc, VALUE *argv, VALUE str) { int base; if (argc == 0) base = 10; else { VALUE b; rb_scan_args(argc, argv, "01", &b); base = NUM2INT(b); } if (base < 0) { rb_raise(rb_eArgError, "invalid radix %d", base); } return rb_str_to_inum(str, base, FALSE); }
Returns a rational which denotes the string form. The parser ignores leading whitespaces and trailing garbage. Any digit sequences can be separated by an underscore. Returns zero for null or garbage string.
NOTE: '0.3'.to_r isn't the same as 0.3.to_r. The former is equivalent to '3/10'.to_r, but the latter isn't so.
' 2 '.to_r #=> (2/1) '300/2'.to_r #=> (150/1) '-9.2'.to_r #=> (-46/5) '-9.2e2'.to_r #=> (-920/1) '1_234_567'.to_r #=> (1234567/1) '21 june 09'.to_r #=> (21/1) '21/06/09'.to_r #=> (7/2) 'bwv 1079'.to_r #=> (0/1)
See Kernel
.Rational.
static VALUE string_to_r(VALUE self) { char *s; VALUE num; rb_must_asciicompat(self); s = RSTRING_PTR(self); if (s && s[RSTRING_LEN(self)]) { rb_str_modify(self); s = RSTRING_PTR(self); s[RSTRING_LEN(self)] = '\0'; } if (!s) s = (char *)""; (void)parse_rat(s, 0, &num); if (RB_FLOAT_TYPE_P(num)) rb_raise(rb_eFloatDomainError, "Infinity"); return num; }
Returns the Symbol
corresponding to str, creating the symbol if it did not previously exist. See Symbol#id2name
.
"Koala".intern #=> :Koala s = 'cat'.to_sym #=> :cat s == :cat #=> true s = '@cat'.to_sym #=> :@cat s == :@cat #=> true
This can also be used to create symbols that cannot be represented using the :xxx
notation.
'cat and dog'.to_sym #=> :"cat and dog"
VALUE rb_str_intern(VALUE str) { #if USE_SYMBOL_GC rb_encoding *enc, *ascii; int type; #else ID id; #endif VALUE sym = lookup_str_sym(str); if (sym) { return sym; } #if USE_SYMBOL_GC enc = rb_enc_get(str); ascii = rb_usascii_encoding(); if (enc != ascii && sym_check_asciionly(str)) { str = rb_str_dup(str); rb_enc_associate(str, ascii); OBJ_FREEZE(str); enc = ascii; } else { str = rb_str_new_frozen(str); } str = rb_fstring(str); type = rb_str_symname_type(str, IDSET_ATTRSET_FOR_INTERN); if (type < 0) type = ID_JUNK; return dsymbol_alloc(rb_cSymbol, str, enc, type); #else id = intern_str(str, 0); return ID2SYM(id); #endif }
Returns a copy of str
with the characters in from_str
replaced by the corresponding characters in to_str
. If to_str
is shorter than from_str
, it is padded with its last character in order to maintain the correspondence.
"hello".tr('el', 'ip') #=> "hippo" "hello".tr('aeiou', '*') #=> "h*ll*" "hello".tr('aeiou', 'AA*') #=> "hAll*"
Both strings may use the c1-c2
notation to denote ranges of characters, and from_str
may start with a ^
, which denotes all characters except those listed.
"hello".tr('a-y', 'b-z') #=> "ifmmp" "hello".tr('^aeiou', '*') #=> "*e**o"
The backslash character \
can be used to escape ^
or -
and is otherwise ignored unless it appears at the end of a range or the end of the from_str
or to_str
:
"hello^world".tr("\\^aeiou", "*") #=> "h*ll**w*rld" "hello-world".tr("a\\-eo", "*") #=> "h*ll**w*rld" "hello\r\nworld".tr("\r", "") #=> "hello\nworld" "hello\r\nworld".tr("\\r", "") #=> "hello\r\nwold" "hello\r\nworld".tr("\\\r", "") #=> "hello\nworld" "X['\\b']".tr("X\\", "") #=> "['b']" "X['\\b']".tr("X-\\]", "") #=> "'b'"
static VALUE rb_str_tr(VALUE str, VALUE src, VALUE repl) { str = rb_str_dup(str); tr_trans(str, src, repl, 0); return str; }
Translates str in place, using the same rules as String#tr
. Returns str, or nil
if no changes were made.
static VALUE rb_str_tr_bang(VALUE str, VALUE src, VALUE repl) { return tr_trans(str, src, repl, 0); }
Processes a copy of str as described under String#tr
, then removes duplicate characters in regions that were affected by the translation.
"hello".tr_s('l', 'r') #=> "hero" "hello".tr_s('el', '*') #=> "h*o" "hello".tr_s('el', 'hx') #=> "hhxo"
static VALUE rb_str_tr_s(VALUE str, VALUE src, VALUE repl) { str = rb_str_dup(str); tr_trans(str, src, repl, 1); return str; }
Performs String#tr_s
processing on str in place, returning str, or nil
if no changes were made.
static VALUE rb_str_tr_s_bang(VALUE str, VALUE src, VALUE repl) { return tr_trans(str, src, repl, 1); }
Decodes str (which may contain binary data) according to the format string, returning an array of each value extracted. The format string consists of a sequence of single-character directives, summarized in the table at the end of this entry. Each directive may be followed by a number, indicating the number of times to repeat with this directive. An asterisk (“*
'') will use up all remaining elements. The directives sSiIlL
may each be followed by an underscore (“_
'') or exclamation mark (“!
'') to use the underlying platform's native size for the specified type; otherwise, it uses a platform-independent consistent size. Spaces are ignored in the format string. See also String#unpack1
, Array#pack
.
"abc \0\0abc \0\0".unpack('A6Z6') #=> ["abc", "abc "] "abc \0\0".unpack('a3a3') #=> ["abc", " \000\000"] "abc \0abc \0".unpack('Z*Z*') #=> ["abc ", "abc "] "aa".unpack('b8B8') #=> ["10000110", "01100001"] "aaa".unpack('h2H2c') #=> ["16", "61", 97] "\xfe\xff\xfe\xff".unpack('sS') #=> [-2, 65534] "now=20is".unpack('M*') #=> ["now is"] "whole".unpack('xax2aX2aX1aX2a') #=> ["h", "e", "l", "l", "o"]
This table summarizes the various formats and the Ruby classes returned by each.
Integer | | Directive | Returns | Meaning ------------------------------------------------------------------ C | Integer | 8-bit unsigned (unsigned char) S | Integer | 16-bit unsigned, native endian (uint16_t) L | Integer | 32-bit unsigned, native endian (uint32_t) Q | Integer | 64-bit unsigned, native endian (uint64_t) J | Integer | pointer width unsigned, native endian (uintptr_t) | | c | Integer | 8-bit signed (signed char) s | Integer | 16-bit signed, native endian (int16_t) l | Integer | 32-bit signed, native endian (int32_t) q | Integer | 64-bit signed, native endian (int64_t) j | Integer | pointer width signed, native endian (intptr_t) | | S_ S! | Integer | unsigned short, native endian I I_ I! | Integer | unsigned int, native endian L_ L! | Integer | unsigned long, native endian Q_ Q! | Integer | unsigned long long, native endian (ArgumentError | | if the platform has no long long type.) J! | Integer | uintptr_t, native endian (same with J) | | s_ s! | Integer | signed short, native endian i i_ i! | Integer | signed int, native endian l_ l! | Integer | signed long, native endian q_ q! | Integer | signed long long, native endian (ArgumentError | | if the platform has no long long type.) j! | Integer | intptr_t, native endian (same with j) | | S> s> S!> s!> | Integer | same as the directives without ">" except L> l> L!> l!> | | big endian I!> i!> | | Q> q> Q!> q!> | | "S>" is same as "n" J> j> J!> j!> | | "L>" is same as "N" | | S< s< S!< s!< | Integer | same as the directives without "<" except L< l< L!< l!< | | little endian I!< i!< | | Q< q< Q!< q!< | | "S<" is same as "v" J< j< J!< j!< | | "L<" is same as "V" | | n | Integer | 16-bit unsigned, network (big-endian) byte order N | Integer | 32-bit unsigned, network (big-endian) byte order v | Integer | 16-bit unsigned, VAX (little-endian) byte order V | Integer | 32-bit unsigned, VAX (little-endian) byte order | | U | Integer | UTF-8 character w | Integer | BER-compressed integer (see Array.pack) Float | | Directive | Returns | Meaning ----------------------------------------------------------------- D d | Float | double-precision, native format F f | Float | single-precision, native format E | Float | double-precision, little-endian byte order e | Float | single-precision, little-endian byte order G | Float | double-precision, network (big-endian) byte order g | Float | single-precision, network (big-endian) byte order String | | Directive | Returns | Meaning ----------------------------------------------------------------- A | String | arbitrary binary string (remove trailing nulls and ASCII spaces) a | String | arbitrary binary string Z | String | null-terminated string B | String | bit string (MSB first) b | String | bit string (LSB first) H | String | hex string (high nibble first) h | String | hex string (low nibble first) u | String | UU-encoded string M | String | quoted-printable, MIME encoding (see RFC2045) m | String | base64 encoded string (RFC 2045) (default) | | base64 encoded string (RFC 4648) if followed by 0 P | String | pointer to a structure (fixed-length string) p | String | pointer to a null-terminated string Misc. | | Directive | Returns | Meaning ----------------------------------------------------------------- @ | --- | skip to the offset given by the length argument X | --- | skip backward one byte x | --- | skip forward one byte
HISTORY
J, J! j, and j! are available since Ruby 2.3.
Q_, Q!, q_, and q! are available since Ruby 2.1.
I!<, i!<, I!>, and i!> are available since Ruby 1.9.3.
static VALUE pack_unpack(VALUE str, VALUE fmt) { int mode = rb_block_given_p() ? UNPACK_BLOCK : UNPACK_ARRAY; return pack_unpack_internal(str, fmt, mode); }
Decodes str (which may contain binary data) according to the format string, returning the first value extracted. See also String#unpack
, Array#pack
.
static VALUE pack_unpack1(VALUE str, VALUE fmt) { return pack_unpack_internal(str, fmt, UNPACK_1); }
Returns a copy of str with all lowercase letters replaced with their uppercase counterparts.
See String#downcase
for meaning of options
and use with different encodings.
"hEllO".upcase #=> "HELLO"
static VALUE rb_str_upcase(int argc, VALUE *argv, VALUE str) { str = rb_str_dup(str); rb_str_upcase_bang(argc, argv, str); return str; }
Upcases the contents of str, returning nil
if no changes were made.
See String#downcase
for meaning of options
and use with different encodings.
static VALUE rb_str_upcase_bang(int argc, VALUE *argv, VALUE str) { rb_encoding *enc; OnigCaseFoldType flags = ONIGENC_CASE_UPCASE; flags = check_case_options(argc, argv, flags); str_modify_keep_cr(str); enc = STR_ENC_GET(str); rb_str_check_dummy_enc(enc); if ((flags&ONIGENC_CASE_ASCII_ONLY) && (enc==rb_utf8_encoding() || rb_enc_mbmaxlen(enc)==1) || (!(flags&ONIGENC_CASE_FOLD_TURKISH_AZERI) && ENC_CODERANGE(str)==ENC_CODERANGE_7BIT)) { char *s = RSTRING_PTR(str), *send = RSTRING_END(str); while (s < send) { unsigned int c = *(unsigned char*)s; if (rb_enc_isascii(c, enc) && 'a' <= c && c <= 'z') { *s = 'A' + (c - 'a'); flags |= ONIGENC_CASE_MODIFIED; } s++; } } else if (flags&ONIGENC_CASE_ASCII_ONLY) rb_str_ascii_casemap(str, &flags, enc); else str_shared_replace(str, rb_str_casemap(str, &flags, enc)); if (ONIGENC_CASE_MODIFIED&flags) return str; return Qnil; }
Iterates through successive values, starting at str and ending at other_str inclusive, passing each value in turn to the block. The String#succ
method is used to generate each value. If optional second argument exclusive is omitted or is false, the last value will be included; otherwise it will be excluded.
If no block is given, an enumerator is returned instead.
"a8".upto("b6") {|s| print s, ' ' } for s in "a8".."b6" print s, ' ' end
produces:
a8 a9 b0 b1 b2 b3 b4 b5 b6 a8 a9 b0 b1 b2 b3 b4 b5 b6
If str and other_str contains only ascii numeric characters, both are recognized as decimal numbers. In addition, the width of string (e.g. leading zeros) is handled appropriately.
"9".upto("11").to_a #=> ["9", "10", "11"] "25".upto("5").to_a #=> [] "07".upto("11").to_a #=> ["07", "08", "09", "10", "11"]
static VALUE rb_str_upto(int argc, VALUE *argv, VALUE beg) { VALUE end, exclusive; rb_scan_args(argc, argv, "11", &end, &exclusive); RETURN_ENUMERATOR(beg, argc, argv); return str_upto_each(beg, end, RTEST(exclusive), str_upto_i, Qnil); }
Returns true for a string which is encoded correctly.
"\xc2\xa1".force_encoding("UTF-8").valid_encoding? #=> true "\xc2".force_encoding("UTF-8").valid_encoding? #=> false "\x80".force_encoding("UTF-8").valid_encoding? #=> false
static VALUE rb_str_valid_encoding_p(VALUE str) { int cr = rb_enc_str_coderange(str); return cr == ENC_CODERANGE_BROKEN ? Qfalse : Qtrue; }