A String object has an arbitrary sequence of bytes, typically representing text or binary data. A String object may be created using String::new or as literals.
String objects differ from Symbol objects in that Symbol objects are designed to be used as identifiers, instead of text or data.
You can create a String object explicitly with:
You can convert certain objects to Strings with:
-
Method String.
Some String methods modify self. Typically, a method whose name ends with ! modifies self and returns self; often a similarly named method (without the !) returns a new string.
In general, if there exist both bang and non-bang version of method, the bang! mutates and the non-bang! does not. However, a method without a bang can also mutate, such as String#replace.
Substitution Methods
These methods perform substitutions:
-
String#sub: One substitution (or none); returns a new string. -
String#sub!: One substitution (or none); returnsself. -
String#gsub: Zero or more substitutions; returns a new string. -
String#gsub!: Zero or more substitutions; returnsself.
Each of these methods takes:
-
A first argument,
pattern(string or regexp), that specifies the substring(s) to be replaced. -
Either of these:
-
A second argument,
replacement(string or hash), that determines the replacing string. -
A block that will determine the replacing string.
-
The examples in this section mostly use methods String#sub and String#gsub; the principles illustrated apply to all four substitution methods.
Argument pattern
Argument pattern is commonly a regular expression:
s = 'hello' s.sub(/[aeiou]/, '*') # => "h*llo" s.gsub(/[aeiou]/, '*') # => "h*ll*" s.gsub(/[aeiou]/, '') # => "hll" s.sub(/ell/, 'al') # => "halo" s.gsub(/xyzzy/, '*') # => "hello" 'THX1138'.gsub(/\d+/, '00') # => "THX00"
When pattern is a string, all its characters are treated as ordinary characters (not as regexp special characters):
'THX1138'.gsub('\d+', '00') # => "THX1138"
String replacement
If replacement is a string, that string will determine the replacing string that is to be substituted for the matched text.
Each of the examples above uses a simple string as the replacing string.
String replacement may contain back-references to the pattern’s captures:
-
\n(n a non-negative integer) refers to$n. -
\k<name>refers to the named capturename.
See regexp.rdoc for details.
Note that within the string replacement, a character combination such as $& is treated as ordinary text, and not as a special match variable. However, you may refer to some special match variables using these combinations:
-
\&and\0correspond to$&, which contains the complete matched text. -
\'corresponds to$', which contains string after match. -
\`corresponds to$`, which contains string before match. -
+corresponds to$+, which contains last capture group.
See regexp.rdoc for details.
Note that \\ is interpreted as an escape, i.e., a single backslash.
Note also that a string literal consumes backslashes. See String Literals for details about string literals.
A back-reference is typically preceded by an additional backslash. For example, if you want to write a back-reference \& in replacement with a double-quoted string literal, you need to write "..\\&..".
If you want to write a non-back-reference string \& in replacement, you need first to escape the backslash to prevent this method from interpreting it as a back-reference, and then you need to escape the backslashes again to prevent a string literal from consuming them: "..\\\\&..".
You may want to use the block form to avoid a lot of backslashes.
Hash replacement
If argument replacement is a hash, and pattern matches one of its keys, the replacing string is the value for that key:
h = {'foo' => 'bar', 'baz' => 'bat'} 'food'.sub('foo', h) # => "bard"
Note that a symbol key does not match:
h = {foo: 'bar', baz: 'bat'} 'food'.sub('foo', h) # => "d"
Block
In the block form, the current match string is passed to the block; the block’s return value becomes the replacing string:
s = '@' '1234'.gsub(/\d/) {|match| s.succ! } # => "ABCD"
Special match variables such as $1, $2, $`, $&, and $' are set appropriately.
What’s Here
First, what’s elsewhere. Class String:
-
Inherits from class Object.
-
Includes module Comparable.
Here, class String provides methods that are useful for:
Methods for Creating a String
::new-
Returns a new string.
::try_convert-
Returns a new string created from a given object.
Methods for a Frozen/Unfrozen String
- #+string
-
Returns a string that is not frozen:
self, if not frozen;self.dupotherwise.
- #-string
-
Returns a string that is frozen:
self, if already frozen;self.freezeotherwise.
freeze-
Freezes
self, if not already frozen; returnsself.
Methods for Querying
Counts
empty?-
Returns
trueifself.lengthis zero;falseotherwise.
bytesize-
Returns the count of bytes.
count-
Returns the count of substrings matching given strings.
Substrings
index-
Returns the index of the first occurrence of a given substring; returns
nilif none found.
rindex-
Returns the index of the last occurrence of a given substring; returns
nilif none found.
include?-
Returns
trueif the string contains a given substring;falseotherwise.
start_with?-
Returns
trueif the string begins with any of the given substrings.
end_with?-
Returns
trueif the string ends with any of the given substrings.
Encodings
unicode_normalized?-
Returns
trueif the string is in Unicode normalized form;falseotherwise.
valid_encoding?-
Returns
trueif the string contains only characters that are valid for its encoding.
ascii_only?-
Returns
trueif the string has only ASCII characters;falseotherwise.
Other
sum-
Returns a basic checksum for the string: the sum of each byte.
hash-
Returns the integer hash code.
Methods for Comparing
- #==, #===
-
Returns
trueif a given other string has the same content asself.
eql?-
Returns
trueif the content is the same as the given other string.
- #<=>
-
Returns -1, 0, or 1 as a given other string is smaller than, equal to, or larger than
self.
casecmp-
Ignoring case, returns -1, 0, or 1 as a given other string is smaller than, equal to, or larger than
self.
casecmp?-
Returns
trueif the string is equal to a given string after Unicode case folding;falseotherwise.
Methods for Modifying a String
Each of these methods modifies self.
Insertion
insert-
Returns
selfwith a given string inserted at a given offset.
<<-
Returns
selfconcatenated with a given string or integer.
Substitution
sub!-
Replaces the first substring that matches a given pattern with a given replacement string; returns
selfif any changes,nilotherwise.
gsub!-
Replaces each substring that matches a given pattern with a given replacement string; returns
selfif any changes,nilotherwise.
replace-
Returns
selfwith its entire content replaced by a given string.
reverse!-
Returns
selfwith its characters in reverse order.
setbyte-
Sets the byte at a given integer offset to a given value; returns the argument.
tr!-
Replaces specified characters in
selfwith specified replacement characters; returnsselfif any changes,nilotherwise.
tr_s!-
Replaces specified characters in
selfwith specified replacement characters, removing duplicates from the substrings that were modified; returnsselfif any changes,nilotherwise.
Casing
capitalize!-
Upcases the initial character and downcases all others; returns
selfif any changes,nilotherwise.
downcase!-
Downcases all characters; returns
selfif any changes,nilotherwise.
upcase!-
Upcases all characters; returns
selfif any changes,nilotherwise.
swapcase!-
Upcases each downcase character and downcases each upcase character; returns
selfif any changes,nilotherwise.
Encoding
encode!-
Returns
selfwith all characters transcoded from one given encoding into another.
unicode_normalize!-
Unicode-normalizes
self; returnsself.
scrub!-
Replaces each invalid byte with a given character; returns
self.
force_encoding-
Changes the encoding to a given encoding; returns
self.
Deletion
clear-
Removes all content, so that
selfis empty; returnsself.
squeeze!-
Removes contiguous duplicate characters; returns
self.
delete!-
Removes characters as determined by the intersection of substring arguments.
lstrip!-
Removes leading whitespace; returns
selfif any changes,nilotherwise.
rstrip!-
Removes trailing whitespace; returns
selfif any changes,nilotherwise.
strip!-
Removes leading and trailing whitespace; returns
selfif any changes,nilotherwise.
chomp!-
Removes trailing record separator, if found; returns
selfif any changes,nilotherwise.
chop!-
Removes trailing whitespace if found, otherwise removes the last character; returns
selfif any changes,nilotherwise.
Methods for Converting to New String
Each of these methods returns a new String based on self, often just a modified copy of self.
Extension
*-
Returns the concatenation of multiple copies of
self,
+-
Returns the concatenation of
selfand a given other string.
center-
Returns a copy of
selfcentered between pad substring.
concat-
Returns the concatenation of
selfwith given other strings.
prepend-
Returns the concatenation of a given other string with
self.
ljust-
Returns a copy of
selfof a given length, right-padded with a given other string.
rjust-
Returns a copy of
selfof a given length, left-padded with a given other string.
Encoding
b-
Returns a copy of
selfwith ASCII-8BIT encoding.
scrub-
Returns a copy of
selfwith each invalid byte replaced with a given character.
unicode_normalize-
Returns a copy of
selfwith each character Unicode-normalized.
encode-
Returns a copy of
selfwith all characters transcoded from one given encoding into another.
Substitution
dump-
Returns a copy of +self with all non-printing characters replaced by xHH notation and all special characters escaped.
undump-
Returns a copy of +self with all
\xNNnotation replace by\uNNNNnotation and all escaped characters unescaped.
sub-
Returns a copy of
selfwith the first substring matching a given pattern replaced with a given replacement string;.
gsub-
Returns a copy of
selfwith each substring that matches a given pattern replaced with a given replacement string.
reverse-
Returns a copy of
selfwith its characters in reverse order.
tr-
Returns a copy of
selfwith specified characters replaced with specified replacement characters.
tr_s-
Returns a copy of
selfwith specified characters replaced with specified replacement characters, removing duplicates from the substrings that were modified.
%-
Returns the string resulting from formatting a given object into
self
Casing
capitalize-
Returns a copy of
selfwith the first character upcased and all other characters downcased.
downcase-
Returns a copy of
selfwith all characters downcased.
upcase-
Returns a copy of
selfwith all characters upcased.
swapcase-
Returns a copy of
selfwith all upcase characters downcased and all downcase characters upcased.
Deletion
delete-
Returns a copy of
selfwith characters removed
delete_prefix-
Returns a copy of
selfwith a given prefix removed.
delete_suffix-
Returns a copy of
selfwith a given suffix removed.
lstrip-
Returns a copy of
selfwith leading whitespace removed.
rstrip-
Returns a copy of
selfwith trailing whitespace removed.
strip-
Returns a copy of
selfwith leading and trailing whitespace removed.
chomp-
Returns a copy of
selfwith a trailing record separator removed, if found.
chop-
Returns a copy of
selfwith trailing whitespace or the last character removed.
squeeze-
Returns a copy of
selfwith contiguous duplicate characters removed.
byteslice-
Returns a substring determined by a given index, start/length, or range.
chr-
Returns the first character.
Duplication
to_s, $to_str-
If
selfis a subclass of String, returnsselfcopied into a String; otherwise, returnsself.
Methods for Converting to Non-String
Each of these methods converts the contents of self to a non-String.
Characters, Bytes, and Clusters
bytes-
Returns an array of the bytes in
self.
chars-
Returns an array of the characters in
self.
codepoints-
Returns an array of the integer ordinals in
self.
getbyte-
Returns an integer byte as determined by a given index.
grapheme_clusters-
Returns an array of the grapheme clusters in
self.
Splitting
lines-
Returns an array of the lines in
self, as determined by a given record separator.
partition-
Returns a 3-element array determined by the first substring that matches a given substring or regexp,
rpartition-
Returns a 3-element array determined by the last substring that matches a given substring or regexp,
split-
Returns an array of substrings determined by a given delimiter – regexp or string – or, if a block given, passes those substrings to the block.
Matching
scan-
Returns an array of substrings matching a given regexp or string, or, if a block given, passes each matching substring to the block.
unpack-
Returns an array of substrings extracted from
selfaccording to a given format.
unpack1-
Returns the first substring extracted from
selfaccording to a given format.
Numerics
hex-
Returns the integer value of the leading characters, interpreted as hexadecimal digits.
oct-
Returns the integer value of the leading characters, interpreted as octal digits.
ord-
Returns the integer ordinal of the first character in
self.
to_i-
Returns the integer value of leading characters, interpreted as an integer.
to_f-
Returns the floating-point value of leading characters, interpreted as a floating-point number.
Strings and Symbols
inspect-
Returns copy of
self, enclosed in double-quotes, with special characters escaped.
Methods for Iterating
each_byte-
Calls the given block with each successive byte in
self.
each_char-
Calls the given block with each successive character in
self.
each_codepoint-
Calls the given block with each successive integer codepoint in
self.
each_grapheme_cluster-
Calls the given block with each successive grapheme cluster in
self.
each_line-
Calls the given block with each successive line in
self, as determined by a given record separator.
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 */
char *new_ptr = ALLOC_N(char, (size_t)capa + termlen);
#if USE_RVARGC
assert(RSTRING(str)->as.embed.len + 1 <= str_embed_capa(str));
memcpy(new_ptr, RSTRING(str)->as.embed.ary, RSTRING(str)->as.embed.len + 1);
#else
memcpy(new_ptr, RSTRING(str)->as.embed.ary, RSTRING_EMBED_LEN_MAX + 1);
#endif
RSTRING(str)->as.heap.ptr = new_ptr;
}
else if (FL_TEST(str, STR_SHARED|STR_NOFREE)) {
const size_t size = (size_t)capa + termlen;
const char *const old_ptr = RSTRING_PTR(str);
const size_t osize = RSTRING(str)->as.heap.len + TERM_LEN(str);
char *new_ptr = ALLOC_N(char, (size_t)capa + termlen);
memcpy(new_ptr, old_ptr, osize < size ? osize : size);
FL_UNSET_RAW(str, STR_SHARED|STR_NOFREE);
RSTRING(str)->as.heap.ptr = new_ptr;
}
else if (STR_HEAP_SIZE(str) != (size_t)capa + termlen) {
SIZED_REALLOC_N(RSTRING(str)->as.heap.ptr, char,
(size_t)capa + termlen, STR_HEAP_SIZE(str));
}
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;
}
Returns a new String that is a copy of string.
With no arguments, returns the empty string with the Encoding ASCII-8BIT:
s = String.new s # => "" s.encoding # => #<Encoding:ASCII-8BIT>
With the single String argument string, returns a copy of string with the same encoding as string:
s = String.new("Que veut dire \u{e7}a?") s # => "Que veut dire \u{e7}a?" s.encoding # => #<Encoding:UTF-8>
Literal strings like "" or here-documents always use script encoding, unlike String.new.
With keyword encoding, returns a copy of str with the specified encoding:
s = String.new(encoding: 'ASCII') s.encoding # => #<Encoding:US-ASCII> s = String.new('foo', encoding: 'ASCII') s.encoding # => #<Encoding:US-ASCII>
Note that these are equivalent:
s0 = String.new('foo', encoding: 'ASCII') s1 = 'foo'.force_encoding('ASCII') s0.encoding == s1.encoding # => true
With keyword capacity, returns a copy of str; the given capacity may set the size of the internal buffer, which may affect performance:
String.new(capacity: 1) # => "" String.new(capacity: 4096) # => ""
The string, encoding, and capacity arguments may all be used together:
String.new('hello', encoding: 'UTF-8', capacity: 25)
static VALUE
rb_str_s_try_convert(VALUE dummy, VALUE str)
{
return rb_check_string_type(str);
}
If object is a String object, returns object.
Otherwise if object responds to :to_str, calls object.to_str and returns the result.
Returns nil if object does not respond to :to_str.
Raises an exception unless object.to_str returns a String object.
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;
}
Concatenates object to self and returns self:
s = 'foo' s << 'bar' # => "foobar" s # => "foobar"
If object is an Integer, the value is considered a codepoint and converted to a character before concatenation:
s = 'foo' s << 33 # => "foo!"
Related: String#concat, which takes multiple arguments.
static VALUE
rb_str_cmp_m(VALUE str1, VALUE str2)
{
int result;
VALUE s = rb_check_string_type(str2);
if (NIL_P(s)) {
return rb_invcmp(str1, str2);
}
result = rb_str_cmp(str1, s);
return INT2FIX(result);
}
Compares self and other_string, returning:
-
-1 if
other_stringis larger. -
0 if the two are equal.
-
1 if
other_stringis smaller. -
nilif the two are incomparable.
Examples:
'foo' <=> 'foo' # => 0 'foo' <=> 'food' # => -1 'food' <=> 'foo' # => 1 'FOO' <=> 'foo' # => -1 'foo' <=> 'FOO' # => 1 'foo' <=> 1 # => nil
static VALUE
rb_str_match(VALUE x, VALUE y)
{
switch (OBJ_BUILTIN_TYPE(y)) {
case T_STRING:
rb_raise(rb_eTypeError, "type mismatch: String given");
case T_REGEXP:
return rb_reg_match(y, x);
default:
return rb_funcall(y, idEqTilde, 1, x);
}
}
Returns the Integer index of the first substring that matches the given regexp, or nil if no match found:
'foo' =~ /f/ # => 0 'foo' =~ /o/ # => 1 'foo' =~ /x/ # => nil
Note: also updates Regexp-related global variables.
If the given object is not a Regexp, returns the value returned by object =~ self.
Note that string =~ regexp is different from regexp =~ string (see Regexp#=~):
number= nil "no. 9" =~ /(?<number>\d+)/ number # => nil (not assigned) /(?<number>\d+)/ =~ "no. 9" number #=> "9"
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 rb_str_eql_internal(str1, str2);
}
Returns true if object has the same length and content; as self; false otherwise:
s = 'foo' s == 'foo' # => true s == 'food' # => false s == 'FOO' # => false
Returns false if the two strings’ encodings are not compatible:
"\u{e4 f6 fc}".encode("ISO-8859-1") == ("\u{c4 d6 dc}") # => false
If object is not an instance of String but responds to to_str, then the two strings are compared using object.==.
static VALUE
str_uminus(VALUE str)
{
if (!BARE_STRING_P(str) && !rb_obj_frozen_p(str)) {
str = rb_str_dup(str);
}
return rb_fstring(str);
}
Returns a frozen, possibly pre-existing copy of the string.
The returned String will be deduplicated as long as it does not have any instance variables set on it.
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]);
}
Returns the substring of self specified by the arguments.
When the single Integer argument index is given, returns the 1-character substring found in self at offset index:
'bar'[2] # => "r"
Counts backward from the end of self if index is negative:
'foo'[-3] # => "f"
Returns nil if index is out of range:
'foo'[3] # => nil 'foo'[-4] # => nil
When the two Integer arguments start and length are given, returns the substring of the given length found in self at offset start:
'foo'[0, 2] # => "fo" 'foo'[0, 0] # => ""
Counts backward from the end of self if start is negative:
'foo'[-2, 2] # => "oo"
Special case: returns a new empty String if start is equal to the length of self:
'foo'[3, 2] # => ""
Returns nil if start is out of range:
'foo'[4, 2] # => nil 'foo'[-4, 2] # => nil
Returns the trailing substring of self if length is large:
'foo'[1, 50] # => "oo"
Returns nil if length is negative:
'foo'[0, -1] # => nil
When the single Range argument range is given, derives start and length values from the given range, and returns values as above:
-
'foo'[0..1]is equivalent to'foo'[0, 2]. -
'foo'[0...1]is equivalent to'foo'[0, 1].
When the Regexp argument regexp is given, and the capture argument is 0, returns the first matching substring found in self, or nil if none found:
'foo'[/o/] # => "o" 'foo'[/x/] # => nil s = 'hello there' s[/[aeiou](.)\1/] # => "ell" s[/[aeiou](.)\1/, 0] # => "ell"
If argument capture is given and not 0, it should be either an Integer capture group index or a String or Symbol capture group name; the method call returns only the specified capture (see Regexp Capturing):
s = 'hello there' s[/[aeiou](.)\1/, 1] # => "l" s[/(?<vowel>[aeiou])(?<non_vowel>[^aeiou])/, "non_vowel"] # => "l" s[/(?<vowel>[aeiou])(?<non_vowel>[^aeiou])/, :vowel] # => "e"
If an invalid capture group index is given, nil is returned. If an invalid capture group name is given, IndexError is raised.
When the single String argument substring is given, returns the substring from self if found, otherwise nil:
'foo'['oo'] # => "oo" 'foo'['xx'] # => nil
String#slice is an alias for String#[].
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]);
}
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.
VALUE
rb_str_times(VALUE str, VALUE times)
{
VALUE str2;
long n, len;
char *ptr2;
int termlen;
if (times == INT2FIX(1)) {
return str_duplicate(rb_cString, str);
}
if (times == INT2FIX(0)) {
str2 = str_alloc_embed(rb_cString, 0);
rb_enc_copy(str2, str);
return str2;
}
len = NUM2LONG(times);
if (len < 0) {
rb_raise(rb_eArgError, "negative argument");
}
if (RSTRING_LEN(str) == 1 && RSTRING_PTR(str)[0] == 0) {
if (STR_EMBEDDABLE_P(len, 1)) {
str2 = str_alloc_embed(rb_cString, len + 1);
memset(RSTRING_PTR(str2), 0, len + 1);
}
else {
str2 = str_alloc_heap(rb_cString);
RSTRING(str2)->as.heap.aux.capa = len;
RSTRING(str2)->as.heap.ptr = ZALLOC_N(char, (size_t)len + 1);
STR_SET_NOEMBED(str2);
}
STR_SET_LEN(str2, len);
rb_enc_copy(str2, str);
return str2;
}
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_cString, 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);
rb_enc_cr_str_copy_for_substr(str2, str);
return str2;
}
Returns a new String containing integer copies of self:
"Ho! " * 3 # => "Ho! Ho! Ho! " "Ho! " * 0 # => ""
static VALUE
rb_str_format_m(VALUE str, VALUE arg)
{
VALUE tmp = rb_check_array_type(arg);
if (!NIL_P(tmp)) {
return rb_str_format(RARRAY_LENINT(tmp), RARRAY_CONST_PTR(tmp), str);
}
return rb_str_format(1, &arg, str);
}
Returns the result of formatting object into the format specification self (see Kernel#sprintf for formatting details):
"%05d" % 123 # => "00123"
If self contains multiple substitutions, object must be an Array or Hash containing the values to be substituted:
"%-5s: %016x" % [ "ID", self.object_id ] # => "ID : 00002b054ec93168" "foo = %{foo}" % {foo: 'bar'} # => "foo = bar" "foo = %{foo}, baz = %{baz}" % {foo: 'bar', baz: 'bat'} # => "foo = bar, baz = bat"
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);
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;
}
Returns a new String containing other_string concatenated to self:
"Hello from " + self.to_s # => "Hello from main"
static VALUE
str_uplus(VALUE str)
{
if (OBJ_FROZEN(str)) {
return rb_str_dup(str);
}
else {
return str;
}
}
Returns self if self is not frozen.
Otherwise. returns self.dup, which is not frozen.
static VALUE
rb_str_is_ascii_only_p(VALUE str)
{
int cr = rb_enc_str_coderange(str);
return RBOOL(cr == ENC_CODERANGE_7BIT);
}
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_b(VALUE str)
{
VALUE str2;
if (FL_TEST(str, STR_NOEMBED)) {
str2 = str_alloc_heap(rb_cString);
}
else {
str2 = str_alloc_embed(rb_cString, RSTRING_EMBED_LEN(str) + TERM_LEN(str));
}
str_replace_shared_without_enc(str2, str);
ENC_CODERANGE_CLEAR(str2);
return str2;
}
Returns a copied string whose encoding is ASCII-8BIT.
static VALUE
rb_str_bytes(VALUE str)
{
VALUE ary = WANTARRAY(