Debian Codegraph @

vendor/mruby-source/mrbgems/mruby-string-ext/mrblib/string.rb

raw
1 class String
2
3 ##
4 # call-seq:
5 # string.clear -> string
6 #
7 # Makes string empty.
8 #
9 # a = "abcde"
10 # a.clear #=> ""
11 #
12 def clear
13 self.replace("")
14 end
15
16 ##
17 # call-seq:
18 # str.lstrip -> new_str
19 #
20 # Returns a copy of <i>str</i> with leading whitespace removed. See also
21 # <code>String#rstrip</code> and <code>String#strip</code>.
22 #
23 # " hello ".lstrip #=> "hello "
24 # "hello".lstrip #=> "hello"
25 #
26 def lstrip
27 a = 0
28 z = self.size - 1
29 a += 1 while a <= z and " \f\n\r\t\v".include?(self[a])
30 (z >= 0) ? self[a..z] : ""
31 end
32
33 ##
34 # call-seq:
35 # str.rstrip -> new_str
36 #
37 # Returns a copy of <i>str</i> with trailing whitespace removed. See also
38 # <code>String#lstrip</code> and <code>String#strip</code>.
39 #
40 # " hello ".rstrip #=> " hello"
41 # "hello".rstrip #=> "hello"
42 #
43 def rstrip
44 a = 0
45 z = self.size - 1
46 z -= 1 while a <= z and " \f\n\r\t\v\0".include?(self[z])
47 (z >= 0) ? self[a..z] : ""
48 end
49
50 ##
51 # call-seq:
52 # str.strip -> new_str
53 #
54 # Returns a copy of <i>str</i> with leading and trailing whitespace removed.
55 #
56 # " hello ".strip #=> "hello"
57 # "\tgoodbye\r\n".strip #=> "goodbye"
58 #
59 def strip
60 a = 0
61 z = self.size - 1
62 a += 1 while a <= z and " \f\n\r\t\v".include?(self[a])
63 z -= 1 while a <= z and " \f\n\r\t\v\0".include?(self[z])
64 (z >= 0) ? self[a..z] : ""
65 end
66
67 ##
68 # call-seq:
69 # str.lstrip! -> self or nil
70 #
71 # Removes leading whitespace from <i>str</i>, returning <code>nil</code> if no
72 # change was made. See also <code>String#rstrip!</code> and
73 # <code>String#strip!</code>.
74 #
75 # " hello ".lstrip #=> "hello "
76 # "hello".lstrip! #=> nil
77 #
78 def lstrip!
79 raise FrozenError, "can't modify frozen String" if frozen?
80 s = self.lstrip
81 (s == self) ? nil : self.replace(s)
82 end
83
84 ##
85 # call-seq:
86 # str.rstrip! -> self or nil
87 #
88 # Removes trailing whitespace from <i>str</i>, returning <code>nil</code> if
89 # no change was made. See also <code>String#lstrip!</code> and
90 # <code>String#strip!</code>.
91 #
92 # " hello ".rstrip #=> " hello"
93 # "hello".rstrip! #=> nil
94 #
95 def rstrip!
96 raise FrozenError, "can't modify frozen String" if frozen?
97 s = self.rstrip
98 (s == self) ? nil : self.replace(s)
99 end
100
101 ##
102 # call-seq:
103 # str.strip! -> str or nil
104 #
105 # Removes leading and trailing whitespace from <i>str</i>. Returns
106 # <code>nil</code> if <i>str</i> was not altered.
107 #
108 def strip!
109 raise FrozenError, "can't modify frozen String" if frozen?
110 s = self.strip
111 (s == self) ? nil : self.replace(s)
112 end
113
114 def partition(sep)
115 raise TypeError, "type mismatch: #{sep.class} given" unless sep.is_a? String
116 n = index(sep)
117 unless n.nil?
118 m = n + sep.size
119 [ slice(0, n), sep, slice(m, size - m) ]
120 else
121 [ self[0..-1], "", "" ]
122 end
123 end
124
125 def rpartition(sep)
126 raise TypeError, "type mismatch: #{sep.class} given" unless sep.is_a? String
127 n = rindex(sep)
128 unless n.nil?
129 m = n + sep.size
130 [ slice(0, n), sep, slice(m, size - m) ]
131 else
132 [ "", "", self ]
133 end
134 end
135
136 ##
137 # call-seq:
138 # str.slice!(fixnum) -> new_str or nil
139 # str.slice!(fixnum, fixnum) -> new_str or nil
140 # str.slice!(range) -> new_str or nil
141 # str.slice!(other_str) -> new_str or nil
142 #
143 # Deletes the specified portion from <i>str</i>, and returns the portion
144 # deleted.
145 #
146 # string = "this is a string"
147 # string.slice!(2) #=> "i"
148 # string.slice!(3..6) #=> " is "
149 # string.slice!("r") #=> "r"
150 # string #=> "thsa sting"
151 #
152 def slice!(arg1, arg2=nil)
153 raise FrozenError, "can't modify frozen String" if frozen?
154 raise ArgumentError, "wrong number of arguments (expected 1..2)" if arg1.nil? && arg2.nil?
155
156 if !arg1.nil? && !arg2.nil?
157 idx = arg1
158 idx += self.size if arg1 < 0
159 if idx >= 0 && idx <= self.size && arg2 > 0
160 str = self[idx, arg2]
161 else
162 return nil
163 end
164 else
165 validated = false
166 if arg1.kind_of?(Range)
167 beg = arg1.begin
168 ed = arg1.end
169 beg += self.size if beg < 0
170 ed += self.size if ed < 0
171 ed -= 1 if arg1.exclude_end?
172 validated = true
173 elsif arg1.kind_of?(String)
174 validated = true
175 else
176 idx = arg1
177 idx += self.size if arg1 < 0
178 validated = true if idx >=0 && arg1 < self.size
179 end
180 if validated
181 str = self[arg1]
182 else
183 return nil
184 end
185 end
186 unless str.nil? || str == ""
187 if !arg1.nil? && !arg2.nil?
188 idx = arg1 >= 0 ? arg1 : self.size+arg1
189 str2 = self[0...idx] + self[idx+arg2..-1].to_s
190 else
191 if arg1.kind_of?(Range)
192 idx = beg >= 0 ? beg : self.size+beg
193 idx2 = ed>= 0 ? ed : self.size+ed
194 str2 = self[0...idx] + self[idx2+1..-1].to_s
195 elsif arg1.kind_of?(String)
196 idx = self.index(arg1)
197 str2 = self[0...idx] + self[idx+arg1.size..-1] unless idx.nil?
198 else
199 idx = arg1 >= 0 ? arg1 : self.size+arg1
200 str2 = self[0...idx] + self[idx+1..-1].to_s
201 end
202 end
203 self.replace(str2) unless str2.nil?
204 end
205 str
206 end
207
208 ##
209 # call-seq:
210 # str.insert(index, other_str) -> str
211 #
212 # Inserts <i>other_str</i> before the character at the given
213 # <i>index</i>, modifying <i>str</i>. Negative indices count from the
214 # end of the string, and insert <em>after</em> the given character.
215 # The intent is insert <i>aString</i> so that it starts at the given
216 # <i>index</i>.
217 #
218 # "abcd".insert(0, 'X') #=> "Xabcd"
219 # "abcd".insert(3, 'X') #=> "abcXd"
220 # "abcd".insert(4, 'X') #=> "abcdX"
221 # "abcd".insert(-3, 'X') #=> "abXcd"
222 # "abcd".insert(-1, 'X') #=> "abcdX"
223 #
224 def insert(idx, str)
225 if idx == -1
226 return self << str
227 elsif idx < 0
228 idx += 1
229 end
230 self[idx, 0] = str
231 self
232 end
233
234 ##
235 # call-seq:
236 # str.ljust(integer, padstr=' ') -> new_str
237 #
238 # If <i>integer</i> is greater than the length of <i>str</i>, returns a new
239 # <code>String</code> of length <i>integer</i> with <i>str</i> left justified
240 # and padded with <i>padstr</i>; otherwise, returns <i>str</i>.
241 #
242 # "hello".ljust(4) #=> "hello"
243 # "hello".ljust(20) #=> "hello "
244 # "hello".ljust(20, '1234') #=> "hello123412341234123"
245 def ljust(idx, padstr = ' ')
246 raise ArgumentError, 'zero width padding' if padstr == ''
247 return self if idx <= self.size
248 pad_repetitions = idx / padstr.size
249 padding = (padstr * pad_repetitions)[0, idx-self.size]
250 self + padding
251 end
252
253 ##
254 # call-seq:
255 # str.rjust(integer, padstr=' ') -> new_str
256 #
257 # If <i>integer</i> is greater than the length of <i>str</i>, returns a new
258 # <code>String</code> of length <i>integer</i> with <i>str</i> right justified
259 # and padded with <i>padstr</i>; otherwise, returns <i>str</i>.
260 #
261 # "hello".rjust(4) #=> "hello"
262 # "hello".rjust(20) #=> " hello"
263 # "hello".rjust(20, '1234') #=> "123412341234123hello"
264 def rjust(idx, padstr = ' ')
265 raise ArgumentError, 'zero width padding' if padstr == ''
266 return self if idx <= self.size
267 pad_repetitions = idx / padstr.size
268 padding = (padstr * pad_repetitions)[0, idx-self.size]
269 padding + self
270 end
271
272 ##
273 # call-seq:
274 # str.center(width, padstr=' ') -> new_str
275 #
276 # Centers +str+ in +width+. If +width+ is greater than the length of +str+,
277 # returns a new String of length +width+ with +str+ centered and padded with
278 # +padstr+; otherwise, returns +str+.
279 #
280 # "hello".center(4) #=> "hello"
281 # "hello".center(20) #=> " hello "
282 # "hello".center(20, '123') #=> "1231231hello12312312"
283 def center(width, padstr = ' ')
284 raise ArgumentError, 'zero width padding' if padstr == ''
285 return self if width <= self.size
286 width -= self.size
287 pad1 = width / 2
288 pad2 = width - pad1
289 (padstr*pad1)[0,pad1] + self + (padstr*pad2)[0,pad2]
290 end
291
292 def chars(&block)
293 if block_given?
294 self.split('').each do |i|
295 block.call(i)
296 end
297 self
298 else
299 self.split('')
300 end
301 end
302
303 ##
304 # Call the given block for each character of
305 # +self+.
306 def each_char(&block)
307 return to_enum :each_char unless block
308 pos = 0
309 while pos < self.size
310 block.call(self[pos])
311 pos += 1
312 end
313 self
314 end
315
316 def codepoints(&block)
317 cp = __codepoints()
318 if block_given?
319 cp.each do|x|
320 block.call(x)
321 end
322 self
323 else
324 cp
325 end
326 end
327 alias each_codepoint codepoints
328
329 ##
330 # call-seq:
331 # str.prepend(other_str) -> str
332 #
333 # Prepend---Prepend the given string to <i>str</i>.
334 #
335 # a = "world"
336 # a.prepend("hello ") #=> "hello world"
337 # a #=> "hello world"
338 def prepend(*args)
339 len = args.size
340 while len > 0
341 len -= 1
342 self[0, 0] = args[len]
343 end
344 self
345 end
346
347 ##
348 # call-seq:
349 # string.lines -> array of string
350 # string.lines {|s| block} -> array of string
351 #
352 # Returns strings per line;
353 #
354 # a = "abc\ndef"
355 # a.lines #=> ["abc\n", "def"]
356 #
357 # If a block is given, it works the same as <code>each_line</code>.
358 def lines(&blk)
359 lines = self.__lines
360 if blk
361 lines.each do |line|
362 blk.call(line)
363 end
364 end
365 lines
366 end
367
368 ##
369 # call-seq:
370 # str.upto(other_str, exclusive=false) {|s| block } -> str
371 # str.upto(other_str, exclusive=false) -> an_enumerator
372 #
373 # Iterates through successive values, starting at <i>str</i> and
374 # ending at <i>other_str</i> inclusive, passing each value in turn to
375 # the block. The <code>String#succ</code> method is used to generate
376 # each value. If optional second argument exclusive is omitted or is false,
377 # the last value will be included; otherwise it will be excluded.
378 #
379 # If no block is given, an enumerator is returned instead.
380 #
381 # "a8".upto("b6") {|s| print s, ' ' }
382 # for s in "a8".."b6"
383 # print s, ' '
384 # end
385 #
386 # <em>produces:</em>
387 #
388 # a8 a9 b0 b1 b2 b3 b4 b5 b6
389 # a8 a9 b0 b1 b2 b3 b4 b5 b6
390 #
391 # If <i>str</i> and <i>other_str</i> contains only ascii numeric characters,
392 # both are recognized as decimal numbers. In addition, the width of
393 # string (e.g. leading zeros) is handled appropriately.
394 #
395 # "9".upto("11").to_a #=> ["9", "10", "11"]
396 # "25".upto("5").to_a #=> []
397 # "07".upto("11").to_a #=> ["07", "08", "09", "10", "11"]
398 def upto(max, exclusive=false, &block)
399 return to_enum(:upto, max, exclusive) unless block
400 raise TypeError, "no implicit conversion of #{max.class} into String" unless max.kind_of? String
401
402 len = self.length
403 maxlen = max.length
404 # single character
405 if len == 1 and maxlen == 1
406 c = self.ord
407 e = max.ord
408 while c <= e
409 break if exclusive and c == e
410 yield c.chr(__ENCODING__)
411 c += 1
412 end
413 return self
414 end
415 # both edges are all digits
416 bi = self.to_i(10)
417 ei = max.to_i(10)
418 if (bi > 0 or bi == "0"*len) and (ei > 0 or ei == "0"*maxlen)
419 while bi <= ei
420 break if exclusive and bi == ei
421 s = bi.to_s
422 s = s.rjust(len, "0") if s.length < len
423 yield s
424 bi += 1
425 end
426 return self
427 end
428 bs = self
429 while true
430 n = (bs <=> max)
431 break if n > 0
432 break if exclusive and n == 0
433 yield bs
434 break if n == 0
435 bsiz = bs.size
436 break if bsiz > max.size || bsiz == 0
437 bs = bs.succ
438 end
439 self
440 end
441
442 def __upto_endless(&block)
443 len = self.length
444 # both edges are all digits
445 bi = self.to_i(10)
446 if bi > 0 or bi == "0"*len
447 while true
448 s = bi.to_s
449 s = s.rjust(len, "0") if s.length < len
450 yield s
451 bi += 1
452 end
453 return self
454 end
455 bs = self
456 while true
457 yield bs
458 bs = bs.succ
459 end
460 self
461 end
462 end