ISO 15.2.10
# 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
private method for gsub/sub
# File mrblib/string.rb, line 55 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
Case-insensitive version of String#<=>
.
"abcdef".casecmp("abcde") #=> 1 "aBcDeF".casecmp("abcdef") #=> 0 "abcdef".casecmp("abcdefg") #=> -1 "abcdef".casecmp("ABCDEF") #=> 0
# File mrbgems/mruby-string-ext/mrblib/string.rb, line 125 def casecmp(str) self.downcase <=> str.__to_str.downcase rescue NoMethodError nil end
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.
# File mrbgems/mruby-string-ext/mrblib/string.rb, line 138 def casecmp?(str) c = self.casecmp(str) return nil if c.nil? return c == 0 end
# File mrbgems/mruby-string-ext/mrblib/string.rb, line 302 def chars(&block) if block_given? self.split('').each do |i| block.call(i) end self else self.split('') end end
Makes string empty.
a = "abcde" a.clear #=> ""
# File mrbgems/mruby-string-ext/mrblib/string.rb, line 12 def clear self.replace("") end
# File mrbgems/mruby-string-ext/mrblib/string.rb, line 326 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
Call the given block for each byte of self
.
# File mrblib/string.rb, line 194 def each_byte(&block) return to_enum(:each_byte, &block) unless block bytes = self.bytes pos = 0 while pos < bytes.size block.call(bytes[pos]) pos += 1 end self end
Call the given block for each character of self
.
# File mrbgems/mruby-string-ext/mrblib/string.rb, line 316 def each_char(&block) return to_enum :each_char unless block pos = 0 while pos < self.size block.call(self[pos]) pos += 1 end self end
Calls the given block for each line and pass the respective line.
ISO 15.2.10.5.15
# File mrblib/string.rb, line 14 def each_line(separator = "\n", &block) return to_enum(:each_line, separator) unless block if separator.nil? block.call(self) return self end raise TypeError unless separator.is_a?(String) paragraph_mode = false if separator.empty? paragraph_mode = true separator = "\n\n" end start = 0 string = dup self_len = length sep_len = separator.length should_yield_subclass_instances = self.class != String while (pointer = string.index(separator, start)) pointer += sep_len pointer += 1 while paragraph_mode && string[pointer] == "\n" if should_yield_subclass_instances block.call(self.class.new(string[start, pointer - start])) else block.call(string[start, pointer - start]) end start = pointer end return self if start == self_len if should_yield_subclass_instances block.call(self.class.new(string[start, self_len - start])) else block.call(string[start, self_len - start]) end self end
# File minirake, line 15 def ext(newext='') return self.dup if ['.', '..'].include? self if newext != '' newext = (newext =~ /^\./) ? newext : ("." + newext) end self.chomp(File.extname(self)) << newext end
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
# File mrblib/string.rb, line 87 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.__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
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
# File mrblib/string.rb, line 125 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 unless self.index(args[0]) self.replace(str) end
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"
# File mrbgems/mruby-string-ext/mrblib/string.rb, line 254 def insert(idx, str) if idx == -1 return self << str elsif idx < 0 idx += 1 end self[idx, 0] = str self end
Returns strings per line;
a = "abc\ndef" a.lines #=> ["abc\n", "def"]
If a block is given, it works the same as each_line
.
# File mrbgems/mruby-string-ext/mrblib/string.rb, line 365 def lines(&blk) lines = self.__lines if blk lines.each do |line| blk.call(line) end end lines end
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"
# File mrbgems/mruby-string-ext/mrblib/string.rb, line 275 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
Returns a copy of str with leading whitespace removed. See also
String#rstrip
and String#strip
.
" hello ".lstrip #=> "hello " "hello".lstrip #=> "hello"
# File mrbgems/mruby-string-ext/mrblib/string.rb, line 26 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
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
# File mrbgems/mruby-string-ext/mrblib/string.rb, line 78 def lstrip! raise FrozenError, "can't modify frozen String" if frozen? s = self.lstrip (s == self) ? nil : self.replace(s) end
# File mrbgems/mruby-string-ext/mrblib/string.rb, line 144 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
# File minirake, line 23 def pathmap(spec=nil, &block) return self if spec.nil? result = '' spec.scan(/%\{[^}]*\}-?\d*[sdpfnxX%]|%-?\d+d|%.|[^%]+/) do |frag| case frag when '%f' result << File.basename(self) when '%n' result << File.basename(self).ext when '%d' result << File.dirname(self) when '%x' result << File.extname(self) when '%X' result << self.ext when '%p' result << self when '%s' result << (File::ALT_SEPARATOR || File::SEPARATOR) when '%-' # do nothing when '%%' result << "%" when /%(-?\d+)d/ result << pathmap_partial($1.to_i) when /^%\{([^}]*)\}(\d*[dpfnxX])/ patterns, operator = $1, $2 result << pathmap('%' + operator).pathmap_replace(patterns, &block) when /^%/ fail ArgumentError, "Unknown pathmap specifier #{frag} in '#{spec}'" else result << frag end end result end
Prepend—Prepend the given string to str.
a = "world" a.prepend("hello ") #=> "hello world" a #=> "hello world"
# File mrbgems/mruby-string-ext/mrblib/string.rb, line 349 def prepend(arg) self[0, 0] = arg self end
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"
# File mrbgems/mruby-string-ext/mrblib/string.rb, line 294 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
# File mrbgems/mruby-string-ext/mrblib/string.rb, line 155 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
Returns a copy of str with trailing whitespace removed. See also
String#lstrip
and String#strip
.
" hello ".rstrip #=> " hello" "hello".rstrip #=> "hello"
# File mrbgems/mruby-string-ext/mrblib/string.rb, line 43 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
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
# File mrbgems/mruby-string-ext/mrblib/string.rb, line 95 def rstrip! raise FrozenError, "can't modify frozen String" if frozen? s = self.rstrip (s == self) ? nil : self.replace(s) end
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"
# File mrbgems/mruby-string-ext/mrblib/string.rb, line 182 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
Returns a copy of str with leading and trailing whitespace removed.
" hello ".strip #=> "hello" "\tgoodbye\r\n".strip #=> "goodbye"
# File mrbgems/mruby-string-ext/mrblib/string.rb, line 59 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
Removes leading and trailing whitespace from str. Returns
nil
if str was not altered.
# File mrbgems/mruby-string-ext/mrblib/string.rb, line 108 def strip! raise FrozenError, "can't modify frozen String" if frozen? s = self.strip (s == self) ? nil : self.replace(s) end
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
# File mrblib/string.rb, line 150 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.__to_str if args.length == 2 && block block = nil end unless block 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
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
# File mrblib/string.rb, line 185 def sub!(*args, &block) raise FrozenError, "can't modify frozen String" if frozen? str = self.sub(*args, &block) return nil unless self.index(args[0]) self.replace(str) end
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"]
# File mrbgems/mruby-string-ext/mrblib/string.rb, line 405 def upto(max, exclusive=false, &block) return to_enum(:upto, max, exclusive) unless block raise TypeError, "no implicit conversion of #{max.class} into String" unless max.kind_of? String len = self.length maxlen = max.length # single character if len == 1 and maxlen == 1 c = self.ord e = max.ord while c <= e break if exclusive and c == e yield c.chr(__ENCODING__) c += 1 end return self end # both edges are all digits bi = self.to_i(10) ei = max.to_i(10) len = self.length if (bi > 0 or bi == "0"*len) and (ei > 0 or ei == "0"*maxlen) while bi <= ei break if exclusive and bi == ei s = bi.to_s s = s.rjust(len, "0") if s.length < len yield s bi += 1 end return self end bs = self while true n = (bs <=> max) break if n > 0 break if exclusive and n == 0 yield bs break if n == 0 bs = bs.succ end self end