Class: String

Inherits:
Object show all
Includes:
Comparable
Defined in:
mrblib/string.rb,
src/string.c,
mrblib/string.rb,
mrbgems/mruby-sprintf/mrblib/string.rb,
mrbgems/mruby-string-ext/mrblib/string.rb

Overview

String

ISO 15.2.10

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Comparable

#<, #<=, #>, #>=, #between?, #clamp

Constructor Details

#new(str = "") ⇒ String

Returns a new string object containing a copy of str.


1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
# File 'src/string.c', line 1630

static mrb_value
mrb_str_init(mrb_state *mrb, mrb_value self)
{
  mrb_value str2;

  if (mrb_get_args(mrb, "|S", &str2) == 0) {
    struct RString *s = str_new(mrb, 0, 0);
    str2 = mrb_obj_value(s);
  }
  str_replace(mrb, mrb_str_ptr(self), mrb_str_ptr(str2));
  return self;
}

Class Method Details

.try_convert(obj) ⇒ Object

call-seq: String.try_convert(obj) -> string or nil

Try to convert obj into a String, using to_str method. Returns converted string or nil if obj cannot be converted for any reason.

String.try_convert("str")     #=> "str"
String.try_convert(/re/)      #=> nil

14
15
16
17
18
19
20
# File 'mrbgems/mruby-string-ext/mrblib/string.rb', line 14

def self.try_convert(obj)
  if obj.respond_to?(:to_str)
    obj.to_str
  else
    nil
  end
end

Instance Method Details

#%(args) ⇒ Object


2
3
4
5
6
7
8
# File 'mrbgems/mruby-sprintf/mrblib/string.rb', line 2

def %(args)
  if args.is_a? Array
    sprintf(self, *args)
  else
    sprintf(self, args)
  end
end

#*(integer) ⇒ String

Copy—Returns a new String containing integer copies of the receiver.

“Ho! “ * 3 #=> “Ho! Ho! Ho! “

Returns:


823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
# File 'src/string.c', line 823

static mrb_value
mrb_str_times(mrb_state *mrb, mrb_value self)
{
  mrb_int n,len,times;
  struct RString *str2;
  char *p;

  mrb_get_args(mrb, "i", &times);
  if (times < 0) {
    mrb_raise(mrb, E_ARGUMENT_ERROR, "negative argument");
  }
  if (times && MRB_INT_MAX / times < RSTRING_LEN(self)) {
    mrb_raise(mrb, E_ARGUMENT_ERROR, "argument too big");
  }

  len = RSTRING_LEN(self)*times;
  str2 = str_new(mrb, 0, len);
  str_with_class(mrb, str2, self);
  p = RSTR_PTR(str2);
  if (len > 0) {
    n = RSTRING_LEN(self);
    memcpy(p, RSTRING_PTR(self), n);
    while (n <= len/2) {
      memcpy(p + n, p, n);
      n *= 2;
    }
    memcpy(p + n, p, len-n);
  }
  p[RSTR_LEN(str2)] = '\0';

  return mrb_obj_value(str2);
}

#+Object

String(“abcdefg”) = String(“abcd”) + String(“efg”)

Returns a new string object containing a copy of str.


782
783
784
785
786
787
788
789
# File 'src/string.c', line 782

static mrb_value
mrb_str_plus_m(mrb_state *mrb, mrb_value self)
{
  mrb_value str;

  mrb_get_args(mrb, "S", &str);
  return mrb_str_plus(mrb, self, str);
}

#<<(integer) ⇒ String #concat(integer) ⇒ String #<<(obj) ⇒ String #concat(obj) ⇒ String

Append—Concatenates the given object to str. If the object is a Integer, it is considered as a codepoint, and is converted to a character before concatenation.

a = “hello “ a « “world” #=> “hello world” a.concat(33) #=> “hello world!”

Overloads:


157
158
159
160
161
162
163
164
165
166
167
168
169
# File 'mrbgems/mruby-string-ext/src/string.c', line 157

static mrb_value
mrb_str_concat_m(mrb_state *mrb, mrb_value self)
{
  mrb_value str;

  mrb_get_args(mrb, "o", &str);
  if (mrb_fixnum_p(str))
    str = mrb_fixnum_chr(mrb, str);
  else
    str = mrb_string_type(mrb, str);
  mrb_str_concat(mrb, self, str);
  return self;
}

#<=>(other_str) ⇒ -1, ...

Comparison—Returns -1 if other_str is less than, 0 if other_str is equal to, and +1 if other_str is greater than str. 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. If the variable $= is false, the comparison is based on comparing the binary values of each character in the string. In older versions of Ruby, setting $= allowed case-insensitive comparisons; this is now deprecated in favor of using String#casecmp.

<=> 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

Returns:

  • (-1, 0, +1)

912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
# File 'src/string.c', line 912

static mrb_value
mrb_str_cmp_m(mrb_state *mrb, mrb_value str1)
{
  mrb_value str2;
  mrb_int result;

  mrb_get_args(mrb, "o", &str2);
  if (!mrb_string_p(str2)) {
    if (!mrb_respond_to(mrb, str2, mrb_intern_lit(mrb, "to_s"))) {
      return mrb_nil_value();
    }
    else if (!mrb_respond_to(mrb, str2, mrb_intern_lit(mrb, "<=>"))) {
      return mrb_nil_value();
    }
    else {
      mrb_value tmp = mrb_funcall(mrb, str2, "<=>", 1, str1);

      if (mrb_nil_p(tmp)) return mrb_nil_value();
      if (!mrb_fixnum_p(tmp)) {
        return mrb_funcall(mrb, mrb_fixnum_value(0), "-", 1, tmp);
      }
      result = -mrb_fixnum(tmp);
    }
  }
  else {
    result = mrb_str_cmp(mrb, str1, str2);
  }
  return mrb_fixnum_value(result);
}

#==(obj) ⇒ Boolean

Equality— If obj is not a String, returns false. Otherwise, returns false or true

caution:if str <=> obj returns zero.

Returns:

  • (Boolean)

979
980
981
982
983
984
985
986
987
# File 'src/string.c', line 979

static mrb_value
mrb_str_equal_m(mrb_state *mrb, mrb_value str1)
{
  mrb_value str2;

  mrb_get_args(mrb, "o", &str2);

  return mrb_bool_value(mrb_str_equal(mrb, str1, str2));
}

#=~(re) ⇒ Object

ISO 15.2.10.5.3

Raises:


247
248
249
250
# File 'mrblib/string.rb', line 247

def =~(re)
  raise TypeError, "type mismatch: String given" if re.respond_to? :to_str
  re =~ self
end

#[](fixnum) ⇒ Fixnum? #[](fixnum, fixnum) ⇒ String? #[](range) ⇒ String? #[](regexp) ⇒ String? #[](regexp, fixnum) ⇒ String? #[](other_str) ⇒ String? #slice(fixnum) ⇒ Fixnum? #slice(fixnum, fixnum) ⇒ String? #slice(range) ⇒ String? #slice(other_str) ⇒ String?

Element Reference—If passed a single Fixnum, returns the code of the character at that position. If passed two Fixnum objects, returns a substring starting at the offset given by the first, and a length given by the second. If given a range, a substring containing characters 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.

If a String is given, that string is returned if it occurs in str. In both cases, nil is returned if there is no match.

a = “hello there” a[1] #=> 101(1.8.7) “e”(1.9.2) a[1.1] #=> “e”(1.9.2) a[1,3] #=> “ell” a[1..3] #=> “ell” a[-3,2] #=> “er” a[-4..-2] #=> “her” a[12..-1] #=> nil a[-2..-4] #=> “” a[“lo”] #=> “lo” a[“bye”] #=> nil

Overloads:


1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
# File 'src/string.c', line 1130

static mrb_value
mrb_str_aref_m(mrb_state *mrb, mrb_value str)
{
  mrb_value a1, a2;
  mrb_int argc;

  argc = mrb_get_args(mrb, "o|o", &a1, &a2);
  if (argc == 2) {
    mrb_int n1, n2;

    mrb_regexp_check(mrb, a1);
    mrb_get_args(mrb, "ii", &n1, &n2);
    return str_substr(mrb, str, n1, n2);
  }
  if (argc != 1) {
    mrb_raisef(mrb, E_ARGUMENT_ERROR, "wrong number of arguments (%S for 1)", mrb_fixnum_value(argc));
  }
  return mrb_str_aref(mrb, str, a1);
}

#[]=(*args) ⇒ Object

Modify +self+ by replacing the content of +self+. The portion of the string affected is determined using the same criteria as +String#[]+.


195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
# File 'mrblib/string.rb', line 195

def []=(*args)
  anum = args.size
  if anum == 2
    pos, value = args
    case pos
    when String
      posnum = self.index(pos)
      if posnum
        b = self[0, posnum.to_i]
        a = self[(posnum + pos.length)..-1]
        self.replace([b, value, a].join(''))
      else
        raise IndexError, "string not matched"
      end
    when Range
      head = pos.begin
      tail = pos.end
      tail += self.length if tail < 0
      unless pos.exclude_end?
        tail += 1
      end
      return self[head, tail-head]=value
    else
      pos += self.length if pos < 0
      if pos < 0 || pos > self.length
        raise IndexError, "index #{args[0]} out of string"
      end
      b = self[0, pos.to_i]
      a = self[pos + 1..-1]
      self.replace([b, value, a].join(''))
    end
    return value
  elsif anum == 3
    pos, len, value = args
    pos += self.length if pos < 0
    if pos < 0 || pos > self.length
      raise IndexError, "index #{args[0]} out of string"
    end
    if len < 0
      raise IndexError, "negative length #{len}"
    end
    b = self[0, pos.to_i]
    a = self[pos + len..-1]
    self.replace([b, value, a].join(''))
    return value
  else
    raise ArgumentError, "wrong number of arguments (#{anum} for 2..3)"
  end
end

#__sub_replace(pre, m, post) ⇒ Object

private method for gsub/sub


28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'mrblib/string.rb', line 28

def __sub_replace(pre, m, post)
  s = ""
  i = 0
  while j = index("\\", i)
    break if j == length-1
    t = case self[j+1]
        when "\\"
          "\\"
        when "`"
          pre
        when "&", "0"
          m
        when "'"
          post
        when "1", "2", "3", "4", "5", "6", "7", "8", "9"
          ""
        else
          self[j, 2]
        end
    s += self[i, j-i] + t
    i = j + 2
  end
  s + self[i, length-i]
end

#bytesObject

Returns an array of bytes in str.

str = “hello” str.bytes #=> [104, 101, 108, 108, 111]


2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
# File 'src/string.c', line 2714

static mrb_value
mrb_str_bytes(mrb_state *mrb, mrb_value str)
{
  struct RString *s = mrb_str_ptr(str);
  mrb_value a = mrb_ary_new_capa(mrb, RSTR_LEN(s));
  unsigned char *p = (unsigned char *)(RSTR_PTR(s)), *pend = p + RSTR_LEN(s);

  while (p < pend) {
    mrb_ary_push(mrb, a, mrb_fixnum_value(p[0]));
    p++;
  }
  return a;
}

#bytesizeObject


806
807
808
809
810
811
# File 'src/string.c', line 806

static mrb_value
mrb_str_bytesize(mrb_state *mrb, mrb_value self)
{
  mrb_int len = RSTRING_LEN(self);
  return mrb_fixnum_value(len);
}

#bytesliceObject


42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'mrbgems/mruby-string-ext/src/string.c', line 42

static mrb_value
mrb_str_byteslice(mrb_state *mrb, mrb_value str)
{
  mrb_value a1;
  mrb_int len;

  if (mrb_get_argc(mrb) == 2) {
    mrb_int pos;
    mrb_get_args(mrb, "ii", &pos, &len);
    return mrb_str_substr(mrb, str, pos, len);
  }
  mrb_get_args(mrb, "o|i", &a1, &len);
  switch (mrb_type(a1)) {
  case MRB_TT_RANGE:
    {
      mrb_int beg;

      len = RSTRING_LEN(str);
      switch (mrb_range_beg_len(mrb, a1, &beg, &len, len, TRUE)) {
      case 0:                   /* not range */
        break;
      case 1:                   /* range */
        return mrb_str_substr(mrb, str, beg, len);
      case 2:                   /* out of range */
        mrb_raisef(mrb, E_RANGE_ERROR, "%S out of range", a1);
        break;
      }
      return mrb_nil_value();
    }
#ifndef MRB_WITHOUT_FLOAT
  case MRB_TT_FLOAT:
    a1 = mrb_fixnum_value((mrb_int)mrb_float(a1));
    /* fall through */
#endif
  case MRB_TT_FIXNUM:
    return mrb_str_substr(mrb, str, mrb_fixnum(a1), 1);
  default:
    mrb_raise(mrb, E_TYPE_ERROR, "wrong type of argument");
  }
  /* not reached */
  return mrb_nil_value();
}

#capitalizeString

Returns a copy of str with the first character converted to uppercase and the remainder to lowercase.

“hello”.capitalize #=> “Hello” “HELLO”.capitalize #=> “Hello” “123ABC”.capitalize #=> “123abc”

Returns:


1199
1200
1201
1202
1203
1204
1205
1206
1207
# File 'src/string.c', line 1199

static mrb_value
mrb_str_capitalize(mrb_state *mrb, mrb_value self)
{
  mrb_value str;

  str = mrb_str_dup(mrb, self);
  mrb_str_capitalize_bang(mrb, str);
  return str;
}

#capitalize!String?

Modifies str by converting the first character to uppercase and the remainder to lowercase. Returns nil if no changes are made.

a = “hello” a.capitalize! #=> “Hello” a #=> “Hello” a.capitalize! #=> nil

Returns:


1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
# File 'src/string.c', line 1163

static mrb_value
mrb_str_capitalize_bang(mrb_state *mrb, mrb_value str)
{
  char *p, *pend;
  mrb_bool modify = FALSE;
  struct RString *s = mrb_str_ptr(str);

  mrb_str_modify(mrb, s);
  if (RSTR_LEN(s) == 0 || !RSTR_PTR(s)) return mrb_nil_value();
  p = RSTR_PTR(s); pend = RSTR_PTR(s) + RSTR_LEN(s);
  if (ISLOWER(*p)) {
    *p = TOUPPER(*p);
    modify = TRUE;
  }
  while (++p < pend) {
    if (ISUPPER(*p)) {
      *p = TOLOWER(*p);
      modify = TRUE;
    }
  }
  if (modify) return str;
  return mrb_nil_value();
}

#casecmp(str) ⇒ Object

call-seq: str.casecmp(other_str) -> -1, 0, +1 or nil

Case-insensitive version of String#<=>.

“abcdef”.casecmp(“abcde”) #=> 1 “aBcDeF”.casecmp(“abcdef”) #=> 0 “abcdef”.casecmp(“abcdefg”) #=> -1 “abcdef”.casecmp(“ABCDEF”) #=> 0


144
145
146
147
148
# File 'mrbgems/mruby-string-ext/mrblib/string.rb', line 144

def casecmp(str)
  self.downcase <=> str.to_str.downcase
rescue NoMethodError
  nil
end

#casecmp?(str) ⇒ Boolean

call-seq: str.casecmp?(other) -> true, false, or nil

Returns true if str and other_str are equal after case folding, false if they are not equal, and nil if other_str is not a string.

Returns:

  • (Boolean)

157
158
159
160
161
# File 'mrbgems/mruby-string-ext/mrblib/string.rb', line 157

def casecmp?(str)
  c = self.casecmp(str)
  return nil if c.nil?
  return c == 0
end

#chars(&block) ⇒ Object


321
322
323
324
325
326
327
328
329
330
# File 'mrbgems/mruby-string-ext/mrblib/string.rb', line 321

def chars(&block)
  if block_given?
    self.split('').each do |i|
      block.call(i)
    end
    self
  else
    self.split('')
  end
end

#chomp(separator = "\n") ⇒ String

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).

“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”

Returns:


1304
1305
1306
1307
1308
1309
1310
1311
1312
# File 'src/string.c', line 1304

static mrb_value
mrb_str_chomp(mrb_state *mrb, mrb_value self)
{
  mrb_value str;

  str = mrb_str_dup(mrb, self);
  mrb_str_chomp_bang(mrb, str);
  return str;
}

#chomp!(separator = "\n") ⇒ String?

Modifies str in place as described for String#chomp, returning str, or nil if no modifications were made.

Returns:


1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
# File 'src/string.c', line 1217

static mrb_value
mrb_str_chomp_bang(mrb_state *mrb, mrb_value str)
{
  mrb_value rs;
  mrb_int newline;
  char *p, *pp;
  mrb_int rslen;
  mrb_int len;
  mrb_int argc;
  struct RString *s = mrb_str_ptr(str);

  argc = mrb_get_args(mrb, "|S", &rs);
  mrb_str_modify(mrb, s);
  len = RSTR_LEN(s);
  if (argc == 0) {
    if (len == 0) return mrb_nil_value();
  smart_chomp:
    if (RSTR_PTR(s)[len-1] == '\n') {
      RSTR_SET_LEN(s, RSTR_LEN(s) - 1);
      if (RSTR_LEN(s) > 0 &&
          RSTR_PTR(s)[RSTR_LEN(s)-1] == '\r') {
        RSTR_SET_LEN(s, RSTR_LEN(s) - 1);
      }
    }
    else if (RSTR_PTR(s)[len-1] == '\r') {
      RSTR_SET_LEN(s, RSTR_LEN(s) - 1);
    }
    else {
      return mrb_nil_value();
    }
    RSTR_PTR(s)[RSTR_LEN(s)] = '\0';
    return str;
  }

  if (len == 0 || mrb_nil_p(rs)) return mrb_nil_value();
  p = RSTR_PTR(s);
  rslen = RSTRING_LEN(rs);
  if (rslen == 0) {
    while (len>0 && p[len-1] == '\n') {
      len--;
      if (len>0 && p[len-1] == '\r')
        len--;
    }
    if (len < RSTR_LEN(s)) {
      RSTR_SET_LEN(s, len);
      p[len] = '\0';
      return str;
    }
    return mrb_nil_value();
  }
  if (rslen > len) return mrb_nil_value();
  newline = RSTRING_PTR(rs)[rslen-1];
  if (rslen == 1 && newline == '\n')
    newline = RSTRING_PTR(rs)[rslen-1];
  if (rslen == 1 && newline == '\n')
    goto smart_chomp;

  pp = p + len - rslen;
  if (p[len-1] == newline &&
     (rslen <= 1 ||
     memcmp(RSTRING_PTR(rs), pp, rslen) == 0)) {
    RSTR_SET_LEN(s, len - rslen);
    p[RSTR_LEN(s)] = '\0';
    return str;
  }
  return mrb_nil_value();
}

#chopString

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 #=> “”

Returns:


1373
1374
1375
1376
1377
1378
1379
1380
# File 'src/string.c', line 1373

static mrb_value
mrb_str_chop(mrb_state *mrb, mrb_value self)
{
  mrb_value str;
  str = mrb_str_dup(mrb, self);
  mrb_str_chop_bang(mrb, str);
  return str;
}

#chop!String?

Processes str as for String#chop, returning str, or nil if str is the empty string. See also String#chomp!.

Returns:


1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
# File 'src/string.c', line 1323

static mrb_value
mrb_str_chop_bang(mrb_state *mrb, mrb_value str)
{
  struct RString *s = mrb_str_ptr(str);

  mrb_str_modify(mrb, s);
  if (RSTR_LEN(s) > 0) {
    mrb_int len;
#ifdef MRB_UTF8_STRING
    const char* t = RSTR_PTR(s), *p = t;
    const char* e = p + RSTR_LEN(s);
    while (p<e) {
      mrb_int clen = utf8len(p, e);
      if (p + clen>=e) break;
      p += clen;
    }
    len = p - t;
#else
    len = RSTR_LEN(s) - 1;
#endif
    if (RSTR_PTR(s)[len] == '\n') {
      if (len > 0 &&
          RSTR_PTR(s)[len-1] == '\r') {
        len--;
      }
    }
    RSTR_SET_LEN(s, len);
    RSTR_PTR(s)[len] = '\0';
    return str;
  }
  return mrb_nil_value();
}

#chrString

Returns a one-character string at the beginning of the string.

a = “abcde” a.chr #=> “a”

Returns:


259
260
261
262
263
# File 'mrbgems/mruby-string-ext/src/string.c', line 259

static mrb_value
mrb_str_chr(mrb_state *mrb, mrb_value self)
{
  return mrb_str_substr(mrb, self, 0, 1);
}

#clearObject

call-seq: string.clear -> string

Makes string empty.

a = “abcde” a.clear #=> “”


31
32
33
# File 'mrbgems/mruby-string-ext/mrblib/string.rb', line 31

def clear
  self.replace("")
end

#codepoints(&block) ⇒ Object Also known as: each_codepoint


341
342
343
344
345
346
347
348
349
350
351
352
# File 'mrbgems/mruby-string-ext/mrblib/string.rb', line 341

def codepoints(&block)
  len = self.size

  if block_given?
    self.split('').each do|x|
      block.call(x.ord)
    end
    self
  else
    self.split('').map{|x| x.ord}
  end
end

#<<(integer) ⇒ String #concat(integer) ⇒ String #<<(obj) ⇒ String #concat(obj) ⇒ String

Append—Concatenates the given object to str. If the object is a Integer, it is considered as a codepoint, and is converted to a character before concatenation.

a = “hello “ a « “world” #=> “hello world” a.concat(33) #=> “hello world!”

Overloads:


157
158
159
160
161
162
163
164
165
166
167
168
169
# File 'mrbgems/mruby-string-ext/src/string.c', line 157

static mrb_value
mrb_str_concat_m(mrb_state *mrb, mrb_value self)
{
  mrb_value str;

  mrb_get_args(mrb, "o", &str);
  if (mrb_fixnum_p(str))
    str = mrb_fixnum_chr(mrb, str);
  else
    str = mrb_string_type(mrb, str);
  mrb_str_concat(mrb, self, str);
  return self;
}

#cover?(obj) ⇒ Boolean

Returns true if +obj+ is between the begin and end of the range.

This tests begin <= obj <= end when #exclude_end? is +false+ and begin <= obj < end when #exclude_end? is +true+.

(“a”..”z”).cover?(“c”) #=> true (“a”..”z”).cover?(“5”) #=> false (“a”..”z”).cover?(“cc”) #=> true

Returns:

  • (Boolean)

Returns:

  • (Boolean)

42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'mrbgems/mruby-range-ext/src/range.c', line 42

static mrb_value
mrb_range_cover(mrb_state *mrb, mrb_value range)
{
  mrb_value val;
  struct RRange *r = mrb_range_ptr(mrb, range);
  mrb_value beg, end;

  mrb_get_args(mrb, "o", &val);

  beg = r->edges->beg;
  end = r->edges->end;

  if (r_le(mrb, beg, val)) {
    if (r->excl) {
      if (r_lt(mrb, val, end))
        return mrb_true_value();
    }
    else {
      if (r_le(mrb, val, end))
        return mrb_true_value();
    }
  }

  return mrb_false_value();
}

#delete_prefix(prefix) ⇒ String

Returns a copy of str with leading prefix deleted.

“hello”.delete_prefix(“hel”) #=> “lo” “hello”.delete_prefix(“llo”) #=> “hello”

Returns:


699
700
701
702
703
704
705
706
707
708
709
710
711
# File 'mrbgems/mruby-string-ext/src/string.c', line 699

static mrb_value
mrb_str_del_prefix(mrb_state *mrb, mrb_value self)
{
  mrb_int plen, slen;
  char *ptr;

  mrb_get_args(mrb, "s", &ptr, &plen);
  slen = RSTRING_LEN(self);
  if (plen > slen) return mrb_str_dup(mrb, self);
  if (memcmp(RSTRING_PTR(self), ptr, plen) != 0)
    return mrb_str_dup(mrb, self);
  return mrb_str_substr(mrb, self, plen, slen-plen);
}

#delete_prefix!(prefix) ⇒ self?

Deletes leading prefix from str, returning nil if no change was made.

“hello”.delete_prefix!(“hel”) #=> “lo” “hello”.delete_prefix!(“llo”) #=> nil

Returns:

  • (self, nil)

666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
# File 'mrbgems/mruby-string-ext/src/string.c', line 666

static mrb_value
mrb_str_del_prefix_bang(mrb_state *mrb, mrb_value self)
{
  mrb_int plen, slen;
  char *ptr, *s;
  struct RString *str = RSTRING(self);

  mrb_get_args(mrb, "s", &ptr, &plen);
  slen = RSTR_LEN(str);
  if (plen > slen) return mrb_nil_value();
  s = RSTR_PTR(str);
  if (memcmp(s, ptr, plen) != 0) return mrb_nil_value();
  if (!MRB_FROZEN_P(str) && (RSTR_SHARED_P(str) || RSTR_FSHARED_P(str))) {
    str->as.heap.ptr += plen;
  }
  else {
    mrb_str_modify(mrb, str);
    s = RSTR_PTR(str);
    memmove(s, s+plen, slen-plen);
  }
  RSTR_SET_LEN(str, slen-plen);
  return self;
}

#delete_suffix(suffix) ⇒ String

Returns a copy of str with leading suffix deleted.

“hello”.delete_suffix(“hel”) #=> “lo” “hello”.delete_suffix(“llo”) #=> “hello”

Returns:


754
755
756
757
758
759
760
761
762
763
764
765
766
# File 'mrbgems/mruby-string-ext/src/string.c', line 754

static mrb_value
mrb_str_del_suffix(mrb_state *mrb, mrb_value self)
{
  mrb_int plen, slen;
  char *ptr;

  mrb_get_args(mrb, "s", &ptr, &plen);
  slen = RSTRING_LEN(self);
  if (plen > slen) return mrb_str_dup(mrb, self);
  if (memcmp(RSTRING_PTR(self)+slen-plen, ptr, plen) != 0)
    return mrb_str_dup(mrb, self);
  return mrb_str_substr(mrb, self, 0, slen-plen);
}

#delete_suffix!(suffix) ⇒ self?

Deletes trailing suffix from str, returning nil if no change was made.

“hello”.delete_suffix!(“llo”) #=> “he” “hello”.delete_suffix!(“hel”) #=> nil

Returns:

  • (self, nil)

723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
# File 'mrbgems/mruby-string-ext/src/string.c', line 723

static mrb_value
mrb_str_del_suffix_bang(mrb_state *mrb, mrb_value self)
{
  mrb_int plen, slen;
  char *ptr, *s;
  struct RString *str = RSTRING(self);

  mrb_get_args(mrb, "s", &ptr, &plen);
  slen = RSTR_LEN(str);
  if (plen > slen) return mrb_nil_value();
  s = RSTR_PTR(str);
  if (memcmp(s+slen-plen, ptr, plen) != 0) return mrb_nil_value();
  if (!MRB_FROZEN_P(str) && (RSTR_SHARED_P(str) || RSTR_FSHARED_P(str))) {
    /* no need to modify string */
  }
  else {
    mrb_str_modify(mrb, str);
  }
  RSTR_SET_LEN(str, slen-plen);
  return self;
}

#downcaseString

Returns a copy of str with all uppercase letters replaced with their lowercase counterparts. The operation is locale insensitive—only characters ‘A’ to ‘Z’ are affected.

“hEllO”.downcase #=> “hello”

Returns:


1423
1424
1425
1426
1427
1428
1429
1430
1431
# File 'src/string.c', line 1423

static mrb_value
mrb_str_downcase(mrb_state *mrb, mrb_value self)
{
  mrb_value str;

  str = mrb_str_dup(mrb, self);
  mrb_str_downcase_bang(mrb, str);
  return str;
}

#downcase!String?

Downcases the contents of str, returning nil if no changes were made.

Returns:


1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
# File 'src/string.c', line 1390

static mrb_value
mrb_str_downcase_bang(mrb_state *mrb, mrb_value str)
{
  char *p, *pend;
  mrb_bool modify = FALSE;
  struct RString *s = mrb_str_ptr(str);

  mrb_str_modify(mrb, s);
  p = RSTR_PTR(s);
  pend = RSTR_PTR(s) + RSTR_LEN(s);
  while (p < pend) {
    if (ISUPPER(*p)) {
      *p = TOLOWER(*p);
      modify = TRUE;
    }
    p++;
  }

  if (modify) return str;
  return mrb_nil_value();
}

#dumpString

Produces a version of str with all nonprinting characters replaced by \nnn notation and all special characters escaped.

Returns:


2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
# File 'src/string.c', line 2449

mrb_value
mrb_str_dump(mrb_state *mrb, mrb_value str)
{
  mrb_int len;
  const char *p, *pend;
  char *q;
  struct RString *result;

  len = 2;                  /* "" */
  p = RSTRING_PTR(str); pend = p + RSTRING_LEN(str);
  while (p < pend) {
    unsigned char c = *p++;
    switch (c) {
      case '"':  case '\\':
      case '\n': case '\r':
      case '\t': case '\f':
      case '\013': case '\010': case '\007': case '\033':
        len += 2;
        break;

      case '#':
        len += IS_EVSTR(p, pend) ? 2 : 1;
        break;

      default:
        if (ISPRINT(c)) {
          len++;
        }
        else {
          len += 4;                /* \NNN */
        }
        break;
    }
  }

  result = str_new(mrb, 0, len);
  str_with_class(mrb, result, str);
  p = RSTRING_PTR(str); pend = p + RSTRING_LEN(str);
  q = RSTR_PTR(result);
  *q++ = '"';
  while (p < pend) {
    unsigned char c = *p++;

    switch (c) {
      case '"':
      case '\\':
        *q++ = '\\';
        *q++ = c;
        break;

      case '\n':
        *q++ = '\\';
        *q++ = 'n';
        break;

      case '\r':
        *q++ = '\\';
        *q++ = 'r';
        break;

      case '\t':
        *q++ = '\\';
        *q++ = 't';
        break;

      case '\f':
        *q++ = '\\';
        *q++ = 'f';
        break;

      case '\013':
        *q++ = '\\';
        *q++ = 'v';
        break;

      case '\010':
        *q++ = '\\';
        *q++ = 'b';
        break;

      case '\007':
        *q++ = '\\';
        *q++ = 'a';
        break;

      case '\033':
        *q++ = '\\';
        *q++ = 'e';
        break;

      case '#':
        if (IS_EVSTR(p, pend)) *q++ = '\\';
        *q++ = '#';
        break;

      default:
        if (ISPRINT(c)) {
          *q++ = c;
        }
        else {
          *q++ = '\\';
          *q++ = 'x';
          q[1] = mrb_digitmap[c % 16]; c /= 16;
          q[0] = mrb_digitmap[c % 16];
          q += 2;
        }
    }
  }
  *q = '"';
  return mrb_obj_value(result);
}

#each_byte(&block) ⇒ Object

Call the given block for each byte of +self+.


182
183
184
185
186
187
188
189
190
# File 'mrblib/string.rb', line 182

def each_byte(&block)
  bytes = self.bytes
  pos = 0
  while pos < bytes.size
    block.call(bytes[pos])
    pos += 1
  end
  self
end

#each_char(&block) ⇒ Object

Call the given block for each character of +self+.


171
172
173
174
175
176
177
178
# File 'mrblib/string.rb', line 171

def each_char(&block)
  pos = 0
  while pos < self.size
    block.call(self[pos])
    pos += 1
  end
  self
end

#each_line(rs = "\n", &block) ⇒ Object

Calls the given block for each line and pass the respective line.

ISO 15.2.10.5.15


12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'mrblib/string.rb', line 12

def each_line(rs = "\n", &block)
  return to_enum(:each_line, rs, &block) unless block
  return block.call(self) if rs.nil?
  rs = rs.to_str
  offset = 0
  rs_len = rs.length
  this = dup
  while pos = this.index(rs, offset)
    block.call(this[offset, pos + rs_len - offset])
    offset = pos + rs_len
  end
  block.call(this[offset, this.size - offset]) if this.size > offset
  self
end

#empty?Boolean

Returns true if str has a length of zero.

“hello”.empty? #=> false ““.empty? #=> true

Returns:

  • (Boolean)

Returns:

  • (Boolean)

1443
1444
1445
1446
1447
1448
1449
# File 'src/string.c', line 1443

static mrb_value
mrb_str_empty_p(mrb_state *mrb, mrb_value self)
{
  struct RString *s = mrb_str_ptr(self);

  return mrb_bool_value(RSTR_LEN(s) == 0);
}

#end_with?([suffixes]) ⇒ Boolean

Returns true if +str+ ends with one of the +suffixes+ given.

Returns:

  • (Boolean)

Returns:

  • (Boolean)

213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
# File 'mrbgems/mruby-string-ext/src/string.c', line 213

static mrb_value
mrb_str_end_with(mrb_state *mrb, mrb_value self)
{
  mrb_value *argv, sub;
  mrb_int argc, i;
  mrb_get_args(mrb, "*", &argv, &argc);

  for (i = 0; i < argc; i++) {
    size_t len_l, len_r;
    int ai = mrb_gc_arena_save(mrb);
    sub = mrb_string_type(mrb, argv[i]);
    mrb_gc_arena_restore(mrb, ai);
    len_l = RSTRING_LEN(self);
    len_r = RSTRING_LEN(sub);
    if (len_l >= len_r) {
      if (memcmp(RSTRING_PTR(self) + (len_l - len_r),
                 RSTRING_PTR(sub),
                 len_r) == 0) {
        return mrb_true_value();
      }
    }
  }
  return mrb_false_value();
}

#eql?(other) ⇒ Boolean

Two strings are equal if the have the same length and content.

Returns:

  • (Boolean)

Returns:

  • (Boolean)

1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
# File 'src/string.c', line 1458

static mrb_value
mrb_str_eql(mrb_state *mrb, mrb_value self)
{
  mrb_value str2;
  mrb_bool eql_p;

  mrb_get_args(mrb, "o", &str2);
  eql_p = (mrb_type(str2) == MRB_TT_STRING) && str_eql(mrb, self, str2);

  return mrb_bool_value(eql_p);
}

#getbyteObject


8
9
10
11
12
13
14
15
16
17
18
19
20
# File 'mrbgems/mruby-string-ext/src/string.c', line 8

static mrb_value
mrb_str_getbyte(mrb_state *mrb, mrb_value str)
{
  mrb_int pos;
  mrb_get_args(mrb, "i", &pos);

  if (pos < 0)
    pos += RSTRING_LEN(str);
  if (pos < 0 ||  RSTRING_LEN(str) <= pos)
    return mrb_nil_value();

  return mrb_fixnum_value((unsigned char)RSTRING_PTR(str)[pos]);
}

#gsub(*args, &block) ⇒ Object

Replace all matches of +pattern+ with +replacement+. Call block (if given) for each match and replace +pattern+ with the value of the block. Return the final value.

ISO 15.2.10.5.18

Raises:


60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# File 'mrblib/string.rb', line 60

def gsub(*args, &block)
  return to_enum(:gsub, *args) if args.length == 1 && !block
  raise ArgumentError, "wrong number of arguments" unless (1..2).include?(args.length)

  pattern, replace = *args
  plen = pattern.length
  if args.length == 2 && block
    block = nil
  end
  if !replace.nil? || !block
    replace = replace.to_str
  end
  offset = 0
  result = []
  while found = index(pattern, offset)
    result << self[offset, found - offset]
    offset = found + plen
    result << if block
      block.call(pattern).to_s
    else
      replace.__sub_replace(self[0, found], pattern, self[offset..-1] || "")
    end
    if plen == 0
      result << self[offset, 1]
      offset += 1
    end
  end
  result << self[offset..-1] if offset < length
  result.join
end

#gsub!(*args, &block) ⇒ Object

Replace all matches of +pattern+ with +replacement+. Call block (if given) for each match and replace +pattern+ with the value of the block. Modify +self+ with the final value.

ISO 15.2.10.5.19

Raises:


98
99
100
101
102
103
104
# File 'mrblib/string.rb', line 98

def gsub!(*args, &block)
  raise FrozenError, "can't modify frozen String" if frozen?
  return to_enum(:gsub!, *args) if args.length == 1 && !block
  str = self.gsub(*args, &block)
  return nil if str == self
  self.replace(str)
end

#hashFixnum

Return a hash based on the string’s length and content.

Returns:


1499
1500
1501
1502
1503
1504
# File 'src/string.c', line 1499

static mrb_value
mrb_str_hash_m(mrb_state *mrb, mrb_value self)
{
  mrb_int key = mrb_str_hash(mrb, self);
  return mrb_fixnum_value(key);
}

#hexObject


238
239
240
241
242
# File 'mrbgems/mruby-string-ext/src/string.c', line 238

static mrb_value
mrb_str_hex(mrb_state *mrb, mrb_value self)
{
  return mrb_str_to_inum(mrb, self, 16, FALSE);
}

#include?(other_str) ⇒ Boolean #include?(fixnum) ⇒ Boolean

Returns true if str contains the given string or character.

“hello”.include? “lo” #=> true “hello”.include? “ol” #=> false “hello”.include? ?h #=> true

Overloads:

  • #include?(other_str) ⇒ Boolean

    Returns:

    • (Boolean)
  • #include?(fixnum) ⇒ Boolean

    Returns:

    • (Boolean)

Returns:

  • (Boolean)

1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
# File 'src/string.c', line 1519

static mrb_value
mrb_str_include(mrb_state *mrb, mrb_value self)
{
  mrb_value str2;

  mrb_get_args(mrb, "S", &str2);
  if (str_index_str(mrb, self, str2, 0) < 0)
    return mrb_bool_value(FALSE);
  return mrb_bool_value(TRUE);
}

#index(substring[, offset]) ⇒ Fixnum? #index(fixnum[, offset]) ⇒ Fixnum? #index(regexp[, offset]) ⇒ Fixnum?

Returns the index of the first occurrence of the given substring, character (fixnum), 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(101) #=> 1(101=0x65=’e’) “hello”.index(/[aeiou]/, -3) #=> 4

Overloads:

  • #index(substring[, offset]) ⇒ Fixnum?

    Returns:

  • #index(fixnum[, offset]) ⇒ Fixnum?

    Returns:

  • #index(regexp[, offset]) ⇒ Fixnum?

    Returns:


1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
# File 'src/string.c', line 1551

static mrb_value
mrb_str_index_m(mrb_state *mrb, mrb_value str)
{
  mrb_value *argv;
  mrb_int argc;
  mrb_value sub;
  mrb_int pos, clen;

  mrb_get_args(mrb, "*!", &argv, &argc);
  if (argc == 2) {
    mrb_get_args(mrb, "oi", &sub, &pos);
  }
  else {
    pos = 0;
    if (argc > 0)
      sub = argv[0];
    else
      sub = mrb_nil_value();
  }
  mrb_regexp_check(mrb, sub);
  clen = RSTRING_CHAR_LEN(str);
  if (pos < 0) {
    pos += clen;
    if (pos < 0) {
      return mrb_nil_value();
    }
  }
  if (pos > clen) return mrb_nil_value();
  pos = chars2bytes(str, 0, pos);

  switch (mrb_type(sub)) {
    default: {
      mrb_value tmp;

      tmp = mrb_check_string_type(mrb, sub);
      if (mrb_nil_p(tmp)) {
        mrb_raisef(mrb, E_TYPE_ERROR, "type mismatch: %S given", sub);
      }
      sub = tmp;
    }
    /* fall through */
    case MRB_TT_STRING:
      pos = str_index_str(mrb, str, sub, pos);
      break;
  }

  if (pos == -1) return mrb_nil_value();
  pos = bytes2chars(RSTRING_PTR(str), pos);
  BYTES_ALIGN_CHECK(pos);
  return mrb_fixnum_value(pos);
}

#replace(other_str) ⇒ String

s = “hello” #=> “hello” s.replace “world” #=> “world”

Returns:


1614
1615
1616
1617
1618
1619
1620
1621
# File 'src/string.c', line 1614

static mrb_value
mrb_str_replace(mrb_state *mrb, mrb_value str)
{
  mrb_value str2;

  mrb_get_args(mrb, "S", &str2);
  return str_replace(mrb, mrb_str_ptr(str), mrb_str_ptr(str2));
}

#insert(idx, str) ⇒ Object

call-seq: str.insert(index, other_str) -> str

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"

273
274
275
276
277
278
279
280
281
# File 'mrbgems/mruby-string-ext/mrblib/string.rb', line 273

def insert(idx, str)
  if idx == -1
    return self << str
  elsif idx < 0
    idx += 1
  end
  self[idx, 0] = str
  self
end

#inspectString

Returns a printable version of str, surrounded by quote marks, with special characters escaped.

str = “hello” str[3] = “\b” str.inspect #=> “"hel\bo"”

Returns:


2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
# File 'src/string.c', line 2638

mrb_value
mrb_str_inspect(mrb_state *mrb, mrb_value str)
{
  const char *p, *pend;
  char buf[CHAR_ESC_LEN + 1];
  mrb_value result = mrb_str_new_lit(mrb, "\"");

  p = RSTRING_PTR(str); pend = RSTRING_END(str);
  for (;p < pend; p++) {
    unsigned char c, cc;
#ifdef MRB_UTF8_STRING
    mrb_int clen;

    clen = utf8len(p, pend);
    if (clen > 1) {
      mrb_int i;

      for (i=0; i<clen; i++) {
        buf[i] = p[i];
      }
      mrb_str_cat(mrb, result, buf, clen);
      p += clen-1;
      continue;
    }
#endif
    c = *p;
    if (c == '"'|| c == '\\' || (c == '#' && IS_EVSTR(p+1, pend))) {
      buf[0] = '\\'; buf[1] = c;
      mrb_str_cat(mrb, result, buf, 2);
      continue;
    }
    if (ISPRINT(c)) {
      buf[0] = c;
      mrb_str_cat(mrb, result, buf, 1);
      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) {
      buf[0] = '\\';
      buf[1] = (char)cc;
      mrb_str_cat(mrb, result, buf, 2);
      continue;
    }
    else {
      buf[0] = '\\';
      buf[1] = 'x';
      buf[3] = mrb_digitmap[c % 16]; c /= 16;
      buf[2] = mrb_digitmap[c % 16];
      mrb_str_cat(mrb, result, buf, 4);
      continue;
    }
  }
  mrb_str_cat_lit(mrb, result, "\"");

  return result;
}

#internObject #to_symObject

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”


1664
1665
1666
1667
1668
# File 'src/string.c', line 1664

MRB_API mrb_value
mrb_str_intern(mrb_state *mrb, mrb_value self)
{
  return mrb_symbol_value(mrb_intern_str(mrb, self));
}

#lastObject #last(n) ⇒ Array

Returns the last object in the range, or an array of the last +n+ elements.

Note that with no arguments +last+ will return the object that defines the end of the range even if #exclude_end? is +true+.

(10..20).last #=> 20 (10…20).last #=> 20 (10..20).last(3) #=> [18, 19, 20] (10…20).last(3) #=> [17, 18, 19]

Overloads:


84
85
86
87
88
89
90
91
92
93
94
95
96
97
# File 'mrbgems/mruby-range-ext/src/range.c', line 84

static mrb_value
mrb_range_last(mrb_state *mrb, mrb_value range)
{
  mrb_value num;
  mrb_value array;
  struct RRange *r = mrb_range_ptr(mrb, range);

  if (mrb_get_args(mrb, "|o", &num) == 0) {
    return r->edges->end;
  }

  array = mrb_funcall(mrb, range, "to_a", 0);
  return mrb_funcall(mrb, array, "last", 1, mrb_to_int(mrb, num));
}

#lengthInteger

Same as sym.to_s.length.

Returns:


799
800
801
802
803
804
# File 'src/string.c', line 799

static mrb_value
mrb_str_size(mrb_state *mrb, mrb_value self)
{
  mrb_int len = RSTRING_CHAR_LEN(self);
  return mrb_fixnum_value(len);
}

#linesObject

Returns strings per line;

a = “abc\ndef” a.lines #=> [“abc\n”, “def”]


319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
# File 'mrbgems/mruby-string-ext/src/string.c', line 319

static mrb_value
mrb_str_lines(mrb_state *mrb, mrb_value self)
{
  mrb_value result;
  mrb_value blk;
  int ai;
  mrb_int len;
  mrb_value arg;
  char *b = RSTRING_PTR(self);
  char *p = b, *t;
  char *e = b + RSTRING_LEN(self);

  mrb_get_args(mrb, "&", &blk);

  result = mrb_ary_new(mrb);
  ai = mrb_gc_arena_save(mrb);
  if (!mrb_nil_p(blk)) {
    while (p < e) {
      t = p;
      while (p < e && *p != '\n') p++;
      if (*p == '\n') p++;
      len = (mrb_int) (p - t);
      arg = mrb_str_new(mrb, t, len);
      mrb_yield_argv(mrb, blk, 1, &arg);
      mrb_gc_arena_restore(mrb, ai);
      if (b != RSTRING_PTR(self)) {
        ptrdiff_t diff = p - b;
        b = RSTRING_PTR(self);
        p = b + diff;
      }
      e = b + RSTRING_LEN(self);
    }
    return self;
  }
  while (p < e) {
    t = p;
    while (p < e && *p != '\n') p++;
    if (*p == '\n') p++;
    len = (mrb_int) (p - t);
    mrb_ary_push(mrb, result, mrb_str_new(mrb, t, len));
    mrb_gc_arena_restore(mrb, ai);
  }
  return result;
}

#ljust(idx, padstr = ' ') ⇒ Object

call-seq: str.ljust(integer, padstr=’ ‘) -> new_str

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"

Raises:


294
295
296
297
298
299
300
# File 'mrbgems/mruby-string-ext/mrblib/string.rb', line 294

def ljust(idx, padstr = ' ')
  raise ArgumentError, 'zero width padding' if padstr == ''
  return self if idx <= self.size
  pad_repetitions = (idx / padstr.length).ceil
  padding = (padstr * pad_repetitions)[0...(idx - self.length)]
  self + padding
end

#lstripObject

call-seq: str.lstrip -> new_str

Returns a copy of str with leading whitespace removed. See also String#rstrip and String#strip.

” hello “.lstrip #=> “hello “ “hello”.lstrip #=> “hello”


45
46
47
48
49
50
# File 'mrbgems/mruby-string-ext/mrblib/string.rb', line 45

def lstrip
  a = 0
  z = self.size - 1
  a += 1 while a <= z and " \f\n\r\t\v".include?(self[a])
  (z >= 0) ? self[a..z] : ""
end

#lstrip!Object

call-seq: str.lstrip! -> self or nil

Removes leading whitespace from str, returning nil if no change was made. See also String#rstrip! and String#strip!.

” hello “.lstrip #=> “hello “ “hello”.lstrip! #=> nil

Raises:


97
98
99
100
101
# File 'mrbgems/mruby-string-ext/mrblib/string.rb', line 97

def lstrip!
  raise FrozenError, "can't modify frozen String" if frozen?
  s = self.lstrip
  (s == self) ? nil : self.replace(s)
end

#match(re, &block) ⇒ Object

ISO 15.2.10.5.27


254
255
256
257
258
259
260
261
262
263
264
265
# File 'mrblib/string.rb', line 254

def match(re, &block)
  if re.respond_to? :to_str
    if Object.const_defined?(:Regexp)
      r = Regexp.new(re)
      r.match(self, &block)
    else
      raise NotImplementedError, "String#match needs Regexp class"
    end
  else
    re.match(self, &block)
  end
end

#octObject


244
245
246
247
248
# File 'mrbgems/mruby-string-ext/src/string.c', line 244

static mrb_value
mrb_str_oct(mrb_state *mrb, mrb_value self)
{
  return mrb_str_to_inum(mrb, self, 8, FALSE);
}

#ordObject


518
519
520
521
522
523
524
# File 'mrbgems/mruby-string-ext/src/string.c', line 518

static mrb_value
mrb_str_ord(mrb_state* mrb, mrb_value str)
{
  if (RSTRING_LEN(str) == 0)
    mrb_raise(mrb, E_ARGUMENT_ERROR, "empty string");
  return mrb_fixnum_value((unsigned char)RSTRING_PTR(str)[0]);
}

#partition(sep) ⇒ Object

Raises:


163
164
165
166
167
168
169
170
171
172
# File 'mrbgems/mruby-string-ext/mrblib/string.rb', line 163

def partition(sep)
  raise TypeError, "type mismatch: #{sep.class} given" unless sep.is_a? String
  n = index(sep)
  unless n.nil?
    m = n + sep.size
    [ slice(0, n), sep, slice(m, size - m) ]
  else
    [ self, "", "" ]
  end
end

#prepend(arg) ⇒ Object

call-seq: str.prepend(other_str) -> str

Prepend—Prepend the given string to str.

a = “world” a.prepend(“hello “) #=> “hello world” a #=> “hello world”


364
365
366
367
# File 'mrbgems/mruby-string-ext/mrblib/string.rb', line 364

def prepend(arg)
  self[0, 0] = arg
  self
end

#replace(other_str) ⇒ String

s = “hello” #=> “hello” s.replace “world” #=> “world”

Returns:


1614
1615
1616
1617
1618
1619
1620
1621
# File 'src/string.c', line 1614

static mrb_value
mrb_str_replace(mrb_state *mrb, mrb_value str)
{
  mrb_value str2;

  mrb_get_args(mrb, "S", &str2);
  return str_replace(mrb, mrb_str_ptr(str), mrb_str_ptr(str2));
}

#reverseString

Returns a new string with the characters from str in reverse order.

“stressed”.reverse #=> “desserts”

Returns:


1795
1796
1797
1798
1799
1800
1801
# File 'src/string.c', line 1795

static mrb_value
mrb_str_reverse(mrb_state *mrb, mrb_value str)
{
  mrb_value str2 = mrb_str_dup(mrb, str);
  mrb_str_reverse_bang(mrb, str2);
  return str2;
}

#reverse!String

Reverses str in place.

Returns:


1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
# File 'src/string.c', line 1733

static mrb_value
mrb_str_reverse_bang(mrb_state *mrb, mrb_value str)
{
#ifdef MRB_UTF8_STRING
  mrb_int utf8_len = RSTRING_CHAR_LEN(str);
  mrb_int len = RSTRING_LEN(str);

  if (utf8_len == len) goto bytes;
  if (utf8_len > 1) {
    char *buf;
    char *p, *e, *r;

    mrb_str_modify(mrb, mrb_str_ptr(str));
    len = RSTRING_LEN(str);
    buf = (char*)mrb_malloc(mrb, (size_t)len);
    p = buf;
    e = buf + len;

    memcpy(buf, RSTRING_PTR(str), len);
    r = RSTRING_PTR(str) + len;

    while (p<e) {
      mrb_int clen = utf8len(p, e);
      r -= clen;
      memcpy(r, p, clen);
      p += clen;
    }
    mrb_free(mrb, buf);
  }
  return str;

 bytes:
#endif
  {
    struct RString *s = mrb_str_ptr(str);
    char *p, *e;
    char c;

    mrb_str_modify(mrb, s);
    if (RSTR_LEN(s) > 1) {
      p = RSTR_PTR(s);
      e = p + RSTR_LEN(s) - 1;
      while (p < e) {
      c = *p;
      *p++ = *e;
      *e-- = c;
      }
    }
    return str;
  }
}

#rindex(substring[, fixnum]) ⇒ Fixnum? #rindex(fixnum[, fixnum]) ⇒ Fixnum? #rindex(regexp[, fixnum]) ⇒ Fixnum?

Returns the index of the last occurrence of the given substring, character (fixnum), 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(101) #=> 1 “hello”.rindex(/[aeiou]/, -2) #=> 1

Overloads:

  • #rindex(substring[, fixnum]) ⇒ Fixnum?

    Returns:

  • #rindex(fixnum[, fixnum]) ⇒ Fixnum?

    Returns:

  • #rindex(regexp[, fixnum]) ⇒ Fixnum?

    Returns:


1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
# File 'src/string.c', line 1822

static mrb_value
mrb_str_rindex(mrb_state *mrb, mrb_value str)
{
  mrb_value *argv;
  mrb_int argc;
  mrb_value sub;
  mrb_int pos, len = RSTRING_CHAR_LEN(str);

  mrb_get_args(mrb, "*!", &argv, &argc);
  if (argc == 2) {
    mrb_get_args(mrb, "oi", &sub, &pos);
    if (pos < 0) {
      pos += len;
      if (pos < 0) {
        mrb_regexp_check(mrb, sub);
        return mrb_nil_value();
      }
    }
    if (pos > len) pos = len;
  }
  else {
    pos = len;
    if (argc > 0)
      sub = argv[0];
    else
      sub = mrb_nil_value();
  }
  pos = chars2bytes(str, 0, pos);
  mrb_regexp_check(mrb, sub);

  switch (mrb_type(sub)) {
    default: {
      mrb_value tmp;

      tmp = mrb_check_string_type(mrb, sub);
      if (mrb_nil_p(tmp)) {
        mrb_raisef(mrb, E_TYPE_ERROR, "type mismatch: %S given", sub);
      }
      sub = tmp;
    }
     /* fall through */
    case MRB_TT_STRING:
      pos = str_rindex(mrb, str, sub, pos);
      if (pos >= 0) {
        pos = bytes2chars(RSTRING_PTR(str), pos);
        BYTES_ALIGN_CHECK(pos);
        return mrb_fixnum_value(pos);
      }
      break;

  } /* end of switch (TYPE(sub)) */
  return mrb_nil_value();
}

#rjust(idx, padstr = ' ') ⇒ Object

call-seq: str.rjust(integer, padstr=’ ‘) -> new_str

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"

Raises:


313
314
315
316
317
318
319
# File 'mrbgems/mruby-string-ext/mrblib/string.rb', line 313

def rjust(idx, padstr = ' ')
  raise ArgumentError, 'zero width padding' if padstr == ''
  return self if idx <= self.size
  pad_repetitions = (idx / padstr.length).ceil
  padding = (padstr * pad_repetitions)[0...(idx - self.length)]
  padding + self
end

#rpartition(sep) ⇒ Object

Raises:


174
175
176
177
178
179
180
181
182
183
# File 'mrbgems/mruby-string-ext/mrblib/string.rb', line 174

def rpartition(sep)
  raise TypeError, "type mismatch: #{sep.class} given" unless sep.is_a? String
  n = rindex(sep)
  unless n.nil?
    m = n + sep.size
    [ slice(0, n), sep, slice(m, size - m) ]
  else
    [ "", "", self ]
  end
end

#rstripObject

call-seq: str.rstrip -> new_str

Returns a copy of str with trailing whitespace removed. See also String#lstrip and String#strip.

” hello “.rstrip #=> “ hello” “hello”.rstrip #=> “hello”


62
63
64
65
66
67
# File 'mrbgems/mruby-string-ext/mrblib/string.rb', line 62

def rstrip
  a = 0
  z = self.size - 1
  z -= 1 while a <= z and " \f\n\r\t\v\0".include?(self[z])
  (z >= 0) ? self[a..z] : ""
end

#rstrip!Object

call-seq: str.rstrip! -> self or nil

Removes trailing whitespace from str, returning nil if no change was made. See also String#lstrip! and String#strip!.

” hello “.rstrip #=> “ hello” “hello”.rstrip! #=> nil

Raises:

  • (RuntimeError)

114
115
116
117
118
# File 'mrbgems/mruby-string-ext/mrblib/string.rb', line 114

def rstrip!
  raise RuntimeError, "can't modify frozen String" if frozen?
  s = self.rstrip
  (s == self) ? nil : self.replace(s)
end

#scan(reg, &block) ⇒ Object

Calls the given block for each match of +pattern+ If no block is given return an array with all matches of +pattern+.

ISO 15.2.10.5.32


112
113
114
115
116
117
# File 'mrblib/string.rb', line 112

def scan(reg, &block)
  ### *** TODO *** ###
  unless Object.const_defined?(:Regexp)
    raise NotImplementedError, "scan not available (yet)"
  end
end

#setbyteObject


22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'mrbgems/mruby-string-ext/src/string.c', line 22

static mrb_value
mrb_str_setbyte(mrb_state *mrb, mrb_value str)
{
  mrb_int pos, byte;
  mrb_int len;

  mrb_get_args(mrb, "ii", &pos, &byte);

  len = RSTRING_LEN(str);
  if (pos < -len || len <= pos)
    mrb_raisef(mrb, E_INDEX_ERROR, "index %S is out of array", mrb_fixnum_value(pos));
  if (pos < 0)
    pos += len;

  mrb_str_modify(mrb, mrb_str_ptr(str));
  byte &= 0xff;
  RSTRING_PTR(str)[pos] = (unsigned char)byte;
  return mrb_fixnum_value((unsigned char)byte);
}

#lengthInteger

Same as sym.to_s.length.

Returns:


799
800
801
802
803
804
# File 'src/string.c', line 799

static mrb_value
mrb_str_size(mrb_state *mrb, mrb_value self)
{
  mrb_int len = RSTRING_CHAR_LEN(self);
  return mrb_fixnum_value(len);
}

#[](fixnum) ⇒ Fixnum? #[](fixnum, fixnum) ⇒ String? #[](range) ⇒ String? #[](regexp) ⇒ String? #[](regexp, fixnum) ⇒ String? #[](other_str) ⇒ String? #slice(fixnum) ⇒ Fixnum? #slice(fixnum, fixnum) ⇒ String? #slice(range) ⇒ String? #slice(other_str) ⇒ String?

Element Reference—If passed a single Fixnum, returns the code of the character at that position. If passed two Fixnum objects, returns a substring starting at the offset given by the first, and a length given by the second. If given a range, a substring containing characters 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.

If a String is given, that string is returned if it occurs in str. In both cases, nil is returned if there is no match.

a = “hello there” a[1] #=> 101(1.8.7) “e”(1.9.2) a[1.1] #=> “e”(1.9.2) a[1,3] #=> “ell” a[1..3] #=> “ell” a[-3,2] #=> “er” a[-4..-2] #=> “her” a[12..-1] #=> nil a[-2..-4] #=> “” a[“lo”] #=> “lo” a[“bye”] #=> nil

Overloads:


1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
# File 'src/string.c', line 1130

static mrb_value
mrb_str_aref_m(mrb_state *mrb, mrb_value str)
{
  mrb_value a1, a2;
  mrb_int argc;

  argc = mrb_get_args(mrb, "o|o", &a1, &a2);
  if (argc == 2) {
    mrb_int n1, n2;

    mrb_regexp_check(mrb, a1);
    mrb_get_args(mrb, "ii", &n1, &n2);
    return str_substr(mrb, str, n1, n2);
  }
  if (argc != 1) {
    mrb_raisef(mrb, E_ARGUMENT_ERROR, "wrong number of arguments (%S for 1)", mrb_fixnum_value(argc));
  }
  return mrb_str_aref(mrb, str, a1);
}

#slice!(arg1, arg2 = nil) ⇒ Object

call-seq: str.slice!(fixnum) -> new_str or nil str.slice!(fixnum, fixnum) -> new_str or nil str.slice!(range) -> new_str or nil str.slice!(other_str) -> new_str or nil

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!(“r”) #=> “r” string #=> “thsa sting”

Raises:


201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
# File 'mrbgems/mruby-string-ext/mrblib/string.rb', line 201

def slice!(arg1, arg2=nil)
  raise FrozenError, "can't modify frozen String" if frozen?
  raise "wrong number of arguments (for 1..2)" if arg1.nil? && arg2.nil?

  if !arg1.nil? && !arg2.nil?
    idx = arg1
    idx += self.size if arg1 < 0
    if idx >= 0 && idx <= self.size && arg2 > 0
      str = self[idx, arg2]
    else
      return nil
    end
  else
    validated = false
    if arg1.kind_of?(Range)
      beg = arg1.begin
      ed = arg1.end
      beg += self.size if beg < 0
      ed += self.size if ed < 0
      ed -= 1 if arg1.exclude_end?
      validated = true
    elsif arg1.kind_of?(String)
      validated = true
    else
      idx = arg1
      idx += self.size if arg1 < 0
      validated = true if idx >=0 && arg1 < self.size
    end
    if validated
      str = self[arg1]
    else
      return nil
    end
  end
  unless str.nil? || str == ""
    if !arg1.nil? && !arg2.nil?
      idx = arg1 >= 0 ? arg1 : self.size+arg1
      str2 = self[0...idx] + self[idx+arg2..-1].to_s
    else
      if arg1.kind_of?(Range)
        idx = beg >= 0 ? beg : self.size+beg
        idx2 = ed>= 0 ? ed : self.size+ed
        str2 = self[0...idx] + self[idx2+1..-1].to_s
      elsif arg1.kind_of?(String)
        idx = self.index(arg1)
        str2 = self[0...idx] + self[idx+arg1.size..-1] unless idx.nil?
      else
        idx = arg1 >= 0 ? arg1 : self.size+arg1
        str2 = self[0...idx] + self[idx+1..-1].to_s
      end
    end
    self.replace(str2) unless str2.nil?
  end
  str
end

#split(pattern = "\n", [limit]) ⇒ Array

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 is omitted, 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.

” 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”] “hello”.split(//) #=> [“h”, “e”, “l”, “l”, “o”] “hello”.split(//, 3) #=> [“h”, “e”, “llo”]

“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”, “”, “”]

Returns:


1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
# File 'src/string.c', line 1917

static mrb_value
mrb_str_split_m(mrb_state *mrb, mrb_value str)
{
  mrb_int argc;
  mrb_value spat = mrb_nil_value();
  enum {awk, string, regexp} split_type = string;
  mrb_int i = 0;
  mrb_int beg;
  mrb_int end;
  mrb_int lim = 0;
  mrb_bool lim_p;
  mrb_value result, tmp;

  argc = mrb_get_args(mrb, "|oi", &spat, &lim);
  lim_p = (lim > 0 && argc == 2);
  if (argc == 2) {
    if (lim == 1) {
      if (RSTRING_LEN(str) == 0)
        return mrb_ary_new_capa(mrb, 0);
      return mrb_ary_new_from_values(mrb, 1, &str);
    }
    i = 1;
  }

  if (argc == 0 || mrb_nil_p(spat)) {
    split_type = awk;
  }
  else {
    if (mrb_string_p(spat)) {
      split_type = string;
      if (RSTRING_LEN(spat) == 1 && RSTRING_PTR(spat)[0] == ' ') {
          split_type = awk;
      }
    }
    else {
      mrb_noregexp(mrb, str);
    }
  }

  result = mrb_ary_new(mrb);
  beg = 0;
  if (split_type == awk) {
    mrb_bool skip = TRUE;
    mrb_int idx = 0;
    mrb_int str_len = RSTRING_LEN(str);
    unsigned int c;
    int ai = mrb_gc_arena_save(mrb);

    idx = end = beg;
    while (idx < str_len) {
      c = (unsigned char)RSTRING_PTR(str)[idx++];
      if (skip) {
        if (ISSPACE(c)) {
          beg = idx;
        }
        else {
          end = idx;
          skip = FALSE;
          if (lim_p && lim <= i) break;
        }
      }
      else if (ISSPACE(c)) {
        mrb_ary_push(mrb, result, byte_subseq(mrb, str, beg, end-beg));
        mrb_gc_arena_restore(mrb, ai);
        skip = TRUE;
        beg = idx;
        if (lim_p) ++i;
      }
      else {
        end = idx;
      }
    }
  }
  else if (split_type == string) {
    mrb_int str_len = RSTRING_LEN(str);
    mrb_int pat_len = RSTRING_LEN(spat);
    mrb_int idx = 0;
    int ai = mrb_gc_arena_save(mrb);

    while (idx < str_len) {
      if (pat_len > 0) {
        end = mrb_memsearch(RSTRING_PTR(spat), pat_len, RSTRING_PTR(str)+idx, str_len - idx);
        if (end < 0) break;
      }
      else {
        end = chars2bytes(str, idx, 1);
      }
      mrb_ary_push(mrb, result, byte_subseq(mrb, str, idx, end));
      mrb_gc_arena_restore(mrb, ai);
      idx += end + pat_len;
      if (lim_p && lim <= ++i) break;
    }
    beg = idx;
  }
  else {
    mrb_noregexp(mrb, str);
  }
  if (RSTRING_LEN(str) > 0 && (lim_p || RSTRING_LEN(str) > beg || lim < 0)) {
    if (RSTRING_LEN(str) == beg) {
      tmp = mrb_str_new_empty(mrb, str);
    }
    else {
      tmp = byte_subseq(mrb, str, beg, RSTRING_LEN(str)-beg);
    }
    mrb_ary_push(mrb, result, tmp);
  }
  if (!lim_p && lim == 0) {
    mrb_int len;
    while ((len = RARRAY_LEN(result)) > 0 &&
           (tmp = RARRAY_PTR(result)[len-1], RSTRING_LEN(tmp) == 0))
      mrb_ary_pop(mrb, result);
  }

  return result;
}

#start_with?([prefixes]) ⇒ Boolean

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 “h”.start_with?(“heaven”, “hell”) #=> false

Returns:

  • (Boolean)

Returns:

  • (Boolean)

184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
# File 'mrbgems/mruby-string-ext/src/string.c', line 184

static mrb_value
mrb_str_start_with(mrb_state *mrb, mrb_value self)
{
  mrb_value *argv, sub;
  mrb_int argc, i;
  mrb_get_args(mrb, "*", &argv, &argc);

  for (i = 0; i < argc; i++) {
    size_t len_l, len_r;
    int ai = mrb_gc_arena_save(mrb);
    sub = mrb_string_type(mrb, argv[i]);
    mrb_gc_arena_restore(mrb, ai);
    len_l = RSTRING_LEN(self);
    len_r = RSTRING_LEN(sub);
    if (len_l >= len_r) {
      if (memcmp(RSTRING_PTR(self), RSTRING_PTR(sub), len_r) == 0) {
        return mrb_true_value();
      }
    }
  }
  return mrb_false_value();
}

#stripObject

call-seq: str.strip -> new_str

Returns a copy of str with leading and trailing whitespace removed.

” hello “.strip #=> “hello” “\tgoodbye\r\n”.strip #=> “goodbye”


78
79
80
81
82
83
84
# File 'mrbgems/mruby-string-ext/mrblib/string.rb', line 78

def strip
  a = 0
  z = self.size - 1
  a += 1 while a <= z and " \f\n\r\t\v".include?(self[a])
  z -= 1 while a <= z and " \f\n\r\t\v\0".include?(self[z])
  (z >= 0) ? self[a..z] : ""
end

#strip!Object

call-seq: str.strip! -> str or nil

Removes leading and trailing whitespace from str. Returns nil if str was not altered.

Raises:


127
128
129
130
131
# File 'mrbgems/mruby-string-ext/mrblib/string.rb', line 127

def strip!
  raise FrozenError, "can't modify frozen String" if frozen?
  s = self.strip
  (s == self) ? nil : self.replace(s)
end

#sub(*args, &block) ⇒ Object

Replace only the first match of +pattern+ with +replacement+. Call block (if given) for each match and replace +pattern+ with the value of the block. Return the final value.

ISO 15.2.10.5.36


126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
# File 'mrblib/string.rb', line 126

def sub(*args, &block)
  unless (1..2).include?(args.length)
    raise ArgumentError, "wrong number of arguments (given #{args.length}, expected 2)"
  end

  pattern, replace = *args
  pattern = pattern.to_str
  if args.length == 2 && block
    block = nil
  end
  unless block
    replace = replace.to_str
  end
  result = []
  this = dup
  found = index(pattern)
  return this unless found
  result << this[0, found]
  offset = found + pattern.length
  result << if block
    block.call(pattern).to_s
  else
    replace.__sub_replace(this[0, found], pattern, this[offset..-1] || "")
  end
  result << this[offset..-1] if offset < length
  result.join
end

#sub!(*args, &block) ⇒ Object

Replace only the first match of +pattern+ with +replacement+. Call block (if given) for each match and replace +pattern+ with the value of the block. Modify +self+ with the final value.

ISO 15.2.10.5.37

Raises:


161
162
163
164
165
166
# File 'mrblib/string.rb', line 161

def sub!(*args, &block)
  raise FrozenError, "can't modify frozen String" if frozen?
  str = self.sub(*args, &block)
  return nil if str == self
  self.replace(str)
end

#succObject


451
452
453
454
455
456
457
458
459
# File 'mrbgems/mruby-string-ext/src/string.c', line 451

static mrb_value
mrb_str_succ(mrb_state *mrb, mrb_value self)
{
  mrb_value str;

  str = mrb_str_dup(mrb, self);
  mrb_str_succ_bang(mrb, str);
  return str;
}

#succString

Returns next sequence of the string;

a = “abc” a.succ #=> “abd”

Returns:


373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
# File 'mrbgems/mruby-string-ext/src/string.c', line 373

static mrb_value
mrb_str_succ_bang(mrb_state *mrb, mrb_value self)
{
  mrb_value result;
  unsigned char *p, *e, *b, *t;
  const char *prepend;
  struct RString *s = mrb_str_ptr(self);
  mrb_int l;

  if (RSTRING_LEN(self) == 0)
    return self;

  mrb_str_modify(mrb, s);
  l = RSTRING_LEN(self);
  b = p = (unsigned char*) RSTRING_PTR(self);
  t = e = p + l;
  *(e--) = 0;

  // find trailing ascii/number
  while (e >= b) {
    if (ISALNUM(*e))
      break;
    e--;
  }
  if (e < b) {
    e = p + l - 1;
    result = mrb_str_new_lit(mrb, "");
  }
  else {
    // find leading letter of the ascii/number
    b = e;
    while (b > p) {
      if (!ISALNUM(*b) || (ISALNUM(*b) && *b != '9' && *b != 'z' && *b != 'Z'))
        break;
      b--;
    }
    if (!ISALNUM(*b))
      b++;
    result = mrb_str_new(mrb, (char*) p, b - p);
  }

  while (e >= b) {
    if (!ISALNUM(*e)) {
      if (*e == 0xff) {
        mrb_str_cat_lit(mrb, result, "\x01");
        (*e) = 0;
      }
      else
        (*e)++;
      break;
    }
    prepend = NULL;
    if (*e == '9') {
      if (e == b) prepend = "1";
      *e = '0';
    }
    else if (*e == 'z') {
      if (e == b) prepend = "a";
      *e = 'a';
    }
    else if (*e == 'Z') {
      if (e == b) prepend = "A";
      *e = 'A';
    }
    else {
      (*e)++;
      break;
    }
    if (prepend) mrb_str_cat_cstr(mrb, result, prepend);
    e--;
  }
  result = mrb_str_cat(mrb, result, (char*) b, t - b);
  l = RSTRING_LEN(result);
  mrb_str_resize(mrb, self, l);
  memcpy(RSTRING_PTR(self), RSTRING_PTR(result), l);
  return self;
}

#swapcaseString

Returns a copy of str with uppercase alphabetic characters converted to lowercase and lowercase characters converted to uppercase. Note: case conversion is effective only in ASCII region.

“Hello”.swapcase #=> “hELLO” “cYbEr_PuNk11”.swapcase #=> “CyBeR_pUnK11”

Returns:


130
131
132
133
134
135
136
137
138
# File 'mrbgems/mruby-string-ext/src/string.c', line 130

static mrb_value
mrb_str_swapcase(mrb_state *mrb, mrb_value self)
{
  mrb_value str;

  str = mrb_str_dup(mrb, self);
  mrb_str_swapcase_bang(mrb, str);
  return str;
}

#swapcase!String?

Equivalent to String#swapcase, but modifies the receiver in place, returning str, or nil if no changes were made. Note: case conversion is effective only in ASCII region.

Returns:


93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
# File 'mrbgems/mruby-string-ext/src/string.c', line 93

static mrb_value
mrb_str_swapcase_bang(mrb_state *mrb, mrb_value str)
{
  char *p, *pend;
  int modify = 0;
  struct RString *s = mrb_str_ptr(str);

  mrb_str_modify(mrb, s);
  p = RSTRING_PTR(str);
  pend = p + RSTRING_LEN(str);
  while (p < pend) {
    if (ISUPPER(*p)) {
      *p = TOLOWER(*p);
      modify = 1;
    }
    else if (ISLOWER(*p)) {
      *p = TOUPPER(*p);
      modify = 1;
    }
    p++;
  }

  if (modify) return str;
  return mrb_nil_value();
}

#to_fFloat

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

Returns:


2365
2366
2367
2368
2369
# File 'src/string.c', line 2365

static mrb_value
mrb_str_to_f(mrb_state *mrb, mrb_value self)
{
  return mrb_float_value(mrb, mrb_str_to_dbl(mrb, self, FALSE));
}

#to_i(base = 10) ⇒ Integer

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.

“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

Returns:


2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
# File 'src/string.c', line 2254

static mrb_value
mrb_str_to_i(mrb_state *mrb, mrb_value self)
{
  mrb_int base = 10;

  mrb_get_args(mrb, "|i", &base);
  if (base < 0) {
    mrb_raisef(mrb, E_ARGUMENT_ERROR, "illegal radix %S", mrb_fixnum_value(base));
  }
  return mrb_str_to_inum(mrb, self, base, FALSE);
}

#to_sString #to_strString

Returns the receiver.

Overloads:


2380
2381
2382
2383
2384
2385
2386
2387
# File 'src/string.c', line 2380

static mrb_value
mrb_str_to_s(mrb_state *mrb, mrb_value self)
{
  if (mrb_obj_class(mrb, self) != mrb->string_class) {
    return mrb_str_dup(mrb, self);
  }
  return self;
}

#to_sString #to_strString

Returns the receiver.

Overloads:


2380
2381
2382
2383
2384
2385
2386
2387
# File 'src/string.c', line 2380

static mrb_value
mrb_str_to_s(mrb_state *mrb, mrb_value self)
{
  if (mrb_obj_class(mrb, self) != mrb->string_class) {
    return mrb_str_dup(mrb, self);
  }
  return self;
}

#internObject #to_symObject

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”


1664
1665
1666
1667
1668
# File 'src/string.c', line 1664

MRB_API mrb_value
mrb_str_intern(mrb_state *mrb, mrb_value self)
{
  return mrb_symbol_value(mrb_intern_str(mrb, self));
}

#upcaseString

Returns a copy of str with all lowercase letters replaced with their uppercase counterparts. The operation is locale insensitive—only characters ‘a’ to ‘z’ are affected.

“hEllO”.upcase #=> “HELLO”

Returns:


2430
2431
2432
2433
2434
2435
2436
2437
2438
# File 'src/string.c', line 2430

static mrb_value
mrb_str_upcase(mrb_state *mrb, mrb_value self)
{
  mrb_value str;

  str = mrb_str_dup(mrb, self);
  mrb_str_upcase_bang(mrb, str);
  return str;
}

#upcase!String?

Upcases the contents of str, returning nil if no changes were made.

Returns:


2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
# File 'src/string.c', line 2397

static mrb_value
mrb_str_upcase_bang(mrb_state *mrb, mrb_value str)
{
  struct RString *s = mrb_str_ptr(str);
  char *p, *pend;
  mrb_bool modify = FALSE;

  mrb_str_modify(mrb, s);
  p = RSTRING_PTR(str);
  pend = RSTRING_END(str);
  while (p < pend) {
    if (ISLOWER(*p)) {
      *p = TOUPPER(*p);
      modify = TRUE;
    }
    p++;
  }

  if (modify) return str;
  return mrb_nil_value();
}

#upto(other_str, exclusive = false) {|s| ... } ⇒ String #upto(other_str, exclusive = false) ⇒ Object

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”]

Overloads:

  • #upto(other_str, exclusive = false) {|s| ... } ⇒ String

    Yields:

    • (s)

    Returns:


568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
# File 'mrbgems/mruby-string-ext/src/string.c', line 568

static mrb_value
mrb_str_upto(mrb_state *mrb, mrb_value beg)
{
  mrb_value end;
  mrb_value exclusive = mrb_false_value();
  mrb_value block = mrb_nil_value();
  mrb_value current, after_end;
  mrb_int n;
  mrb_bool excl;

  mrb_get_args(mrb, "o|o&", &end, &exclusive, &block);

  if (mrb_nil_p(block)) {
    return mrb_funcall(mrb, beg, "to_enum", 3, mrb_symbol_value(mrb_intern_lit(mrb, "upto")), end, exclusive);
  }
  end = mrb_string_type(mrb, end);
  excl = mrb_test(exclusive);

  /* single character */
  if (RSTRING_LEN(beg) == 1 && RSTRING_LEN(end) == 1 &&
  ISASCII(RSTRING_PTR(beg)[0]) && ISASCII(RSTRING_PTR(end)[0])) {
    char c = RSTRING_PTR(beg)[0];
    char e = RSTRING_PTR(end)[0];
    int ai = mrb_gc_arena_save(mrb);

    if (c > e || (excl && c == e)) return beg;
    for (;;) {
      mrb_yield(mrb, block, mrb_str_new(mrb, &c, 1));
      mrb_gc_arena_restore(mrb, ai);
      if (!excl && c == e) break;
      c++;
      if (excl && c == e) break;
    }
    return beg;
  }
  /* both edges are all digits */
  if (ISDIGIT(RSTRING_PTR(beg)[0]) && ISDIGIT(RSTRING_PTR(end)[0]) &&
      all_digits_p(RSTRING_PTR(beg), RSTRING_LEN(beg)) &&
      all_digits_p(RSTRING_PTR(end), RSTRING_LEN(end))) {
    mrb_int min_width = RSTRING_LEN(beg);
    mrb_int bi = mrb_int(mrb, mrb_str_to_inum(mrb, beg, 10, FALSE));
    mrb_int ei = mrb_int(mrb, mrb_str_to_inum(mrb, end, 10, FALSE));
    int ai = mrb_gc_arena_save(mrb);

    while (bi <= ei) {
      mrb_value ns, str;

      if (excl && bi == ei) break;
      ns = mrb_format(mrb, "%S", mrb_fixnum_value(bi));
      if (min_width > RSTRING_LEN(ns)) {
        str = mrb_str_new(mrb, NULL, min_width);
        memset(RSTRING_PTR(str), '0', min_width-RSTRING_LEN(ns));
        memcpy(RSTRING_PTR(str)+min_width-RSTRING_LEN(ns),
               RSTRING_PTR(ns), RSTRING_LEN(ns));
      }
      else {
        str = ns;
      }
      mrb_yield(mrb, block, str);
      mrb_gc_arena_restore(mrb, ai);
      bi++;
    }

    return beg;
  }
  /* normal case */
  n = mrb_int(mrb, mrb_funcall(mrb, beg, "<=>", 1, end));
  if (n > 0 || (excl && n == 0)) return beg;

  after_end = mrb_funcall(mrb, end, "succ", 0);
  current = mrb_str_dup(mrb, beg);
  while (!mrb_str_equal(mrb, current, after_end)) {
    int ai = mrb_gc_arena_save(mrb);
    mrb_value next = mrb_nil_value();
    if (excl || !mrb_str_equal(mrb, current, end))
      next = mrb_funcall(mrb, current, "succ", 0);
    mrb_yield(mrb, block, current);
    if (mrb_nil_p(next)) break;
    current = mrb_str_to_str(mrb, next);
    if (excl && mrb_str_equal(mrb, current, end)) break;
    if (RSTRING_LEN(current) > RSTRING_LEN(end) || RSTRING_LEN(current) == 0)
      break;
    mrb_gc_arena_restore(mrb, ai);
  }

  return beg;
}