Class: String

Inherits:
NSMutableString show all
Includes:
Comparable

Overview

A String object holds and manipulates an arbitrary sequence of bytes, typically representing characters. String objects may be created using String::new or as literals.

Because of aliasing issues, users of strings should be aware of the methods that modify the contents of a String object. Typically, methods with names ending in "!" modify their receiver, while those without a "!" return a new String. However, there are exceptions, such as String#[]=.

Class Method Summary (collapse)

Instance Method Summary (collapse)

Methods included from Comparable

#, #, #>, #>=, #between?

Methods inherited from NSMutableString

#appendFormat:, #appendString:, #deleteCharactersInRange:, #initWithCapacity:, #insertString:atIndex:, #replaceCharactersInRange:withString:, #replaceOccurrencesOfString:withString:options:range:, #setString:, stringWithCapacity:

Methods inherited from NSString

availableStringEncodings, #boolValue, #cStringUsingEncoding:, #canBeConvertedToEncoding:, #capitalizedString, #capitalizedStringWithLocale:, #caseInsensitiveCompare:, #characterAtIndex:, #commonPrefixWithString:options:, #compare:, #compare:options:, #compare:options:range:, #compare:options:range:locale:, #completePathIntoString:caseSensitive:matchesIntoArray:filterTypes:, #componentsSeparatedByCharactersInSet:, #componentsSeparatedByString:, #dataUsingEncoding:, #dataUsingEncoding:allowLossyConversion:, #decomposedStringWithCanonicalMapping, #decomposedStringWithCompatibilityMapping, defaultCStringEncoding, #description, #doubleValue, #encode, #enumerateLinesUsingBlock:, #enumerateLinguisticTagsInRange:scheme:options:orthography:usingBlock:, #enumerateSubstringsInRange:options:usingBlock:, #fastestEncoding, #fileSystemRepresentation, #floatValue, #getBytes:maxLength:usedLength:encoding:options:range:remainingRange:, #getCString:maxLength:encoding:, #getCharacters:range:, #getFileSystemRepresentation:maxLength:, #getLineStart:end:contentsEnd:forRange:, localizedNameOfStringEncoding:, localizedStringWithFormat:, pathWithComponents:, string, stringWithCString:encoding:, stringWithCharacters:length:, stringWithContentsOfFile:encoding:error:, stringWithContentsOfFile:usedEncoding:error:, stringWithContentsOfURL:encoding:error:, stringWithContentsOfURL:usedEncoding:error:, stringWithFormat:, stringWithString:, stringWithUTF8String:

Methods inherited from NSObject

#!, #!=, #!~, #===, #Rational, #__callee__, #__method__, #__send__, #__type__, `, allocWithZone:, #autoContentAccessingProxy, autoload, autoload?, autorelease_pool, #awakeAfterUsingCoder:, binding, block_given?, caller, cancelPreviousPerformRequestsWithTarget:, cancelPreviousPerformRequestsWithTarget:selector:object:, catch, class, classFallbacksForKeyedArchiver, #classForCoder, #classForKeyedArchiver, classForKeyedUnarchiver, #clone, conformsToProtocol:, #copy, copyWithZone:, #dealloc, #define_singleton_method, description, display, #doesNotRecognizeSelector:, #enum_for, #equal?, #extend, fail, #finalize, format, #forwardInvocation:, #forwardingTargetForSelector:, framework, #freeze, #frozen?, getpass, gets, global_variables, #init, initialize, #initialize_clone, #initialize_dup, instanceMethodForSelector:, instanceMethodSignatureForSelector:, #instance_eval, #instance_exec, #instance_of?, #instance_variable_defined?, #instance_variable_get, #instance_variable_set, #instance_variables, instancesRespondToSelector:, isSubclassOfClass:, #is_a?, iterator?, #kind_of?, lambda, load, load_bridge_support_file, load_plist, local_variables, loop, #method, #methodForSelector:, #methodSignatureForSelector:, #methods, #mutableCopy, mutableCopyWithZone:, new, #nil?, open, p, #performSelector:onThread:withObject:waitUntilDone:, #performSelector:onThread:withObject:waitUntilDone:modes:, #performSelector:withObject:afterDelay:, #performSelector:withObject:afterDelay:inModes:, #performSelectorInBackground:withObject:, #performSelectorOnMainThread:withObject:waitUntilDone:, #performSelectorOnMainThread:withObject:waitUntilDone:modes:, print, printf, #private_methods, proc, #protected_methods, #public_method, #public_methods, #public_send, putc, puts, raise, rand, readline, readlines, #replacementObjectForCoder:, #replacementObjectForKeyedArchiver:, require, resolveClassMethod:, resolveInstanceMethod:, #respond_to?, #respond_to_missing?, select, #send, setVersion:, #singleton_methods, sprintf, srand, superclass, #taint, #tainted?, #tap, test, throw, #to_plist, trace_var, trap, #trust, #untaint, untrace_var, #untrust, #untrusted?, version

Constructor Details

- (String) new(str = "")

Returns a new string object containing a copy of str.

Returns:

Dynamic Method Handling

This class handles dynamic methods through the method_missing method in the class NSObject

Class Method Details

+ (Object) alloc

:nodoc:

+ (String?) try_convert(obj)

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

Returns:

Instance Method Details

- (String) %(arg)

Format---Uses str as a format specification, and returns the result of applying it to arg. If the format specification contains more than one substitution, then arg must be an Array or Hash containing the values to be substituted. See Kernel::sprintf for details of the format string.

"%05d" % 123                              #=> "00123"
"%-5s: %08x" % [ "ID", self.object_id ]   #=> "ID   : 200e14d6"
"foo = %{foo}" % { :foo => 'bar' }        #=> "foo = bar"

Returns:

- (String) *(integer)

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

"Ho! " * 3   #=> "Ho! Ho! Ho! "

Returns:

- (String) +(other_str)

Concatenation---Returns a new String containing other_str concatenated to str.

"Hello from " + self.to_s   #=> "Hello from main"

Returns:

- (String) <<(integer) - (String) concat(integer) - (String) <<(obj) - (String) concat(obj)

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:

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

Comparison---Returns -1 if other_str is greater than, 0 if other_str is equal to, and +1 if other_str is less 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. 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, nil)

- (Boolean) ==(obj)

Equality---If obj is not a String, returns false. Otherwise, returns true if str obj returns zero.

Returns:

  • (Boolean)

- (Fixnum?) =~(obj)

Match---If obj is a Regexp, use it as a pattern to match against str,and returns the position the match starts, or nil if there is no match. Otherwise, invokes obj.=~, passing str as an argument. The default =~ in Object returns nil.

"cat o' 9 tails" =~ /\d/   #=> 7
"cat o' 9 tails" =~ 9      #=> nil

Returns:

- (String?) [](fixnum) - (String?) [](fixnum, fixnum) - (String?) [](range) - (String?) [](regexp) - (String?) [](regexp, fixnum) - (String?) [](other_str) - (String?) slice(fixnum) - (String?) slice(fixnum, fixnum) - (String?) slice(range) - (String?) slice(regexp) - (String?) slice(regexp, fixnum) - (String?) slice(regexp, capname) - (String?) slice(other_str)

Element Reference---If passed a single Fixnum, returns a substring of one character at that position. If passed two Fixnum objects, returns a substring starting at the offset given by the first, and with a length given by the second. If passed a range, its beginning and end are interpreted as offsets delimiting the substring to be 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 or the length is negative.

If a Regexp is supplied, the matching portion of str is returned. If a numeric or name parameter follows the regular expression, that component of the MatchData is returned instead. 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]                   #=> "e"
a[2, 3]                #=> "llo"
a[2..3]                #=> "ll"
a[-3, 2]               #=> "er"
a[7..-2]               #=> "her"
a[-4..-2]              #=> "her"
a[-2..-4]              #=> ""
a[12..-1]              #=> nil
a[/[aeiou](.)\1/]      #=> "ell"
a[/[aeiou](.)\1/, 0]   #=> "ell"
a[/[aeiou](.)\1/, 1]   #=> "l"
a[/[aeiou](.)\1/, 2]   #=> nil
a["lo"]                #=> "lo"
a["bye"]               #=> nil

Overloads:

- (Object) []=(fixnum) - (Object) []=(fixnum, fixnum) - (Object) []=(range) - (Object) []=(regexp) - (Object) []=(regexp, fixnum) - (Object) []=(regexp, name) - (Object) []=(other_str)

Element Assignment---Replaces some or all of the content of str. The portion of the string affected is determined using the same criteria as String#[]. If the replacement string is not the same length as the text it is replacing, the string will be adjusted accordingly. If the regular expression or string is used as the index doesn't match a position in the string, IndexError is raised. If the regular expression form is used, the optional second Fixnum allows you to specify which portion of the match to replace (effectively using the MatchData indexing rules. The forms that take a Fixnum will raise an IndexError if the value is out of range; the Range form will raise a RangeError, and the Regexp and String forms will silently ignore the assignment.

- (Boolean) ascii_only?

Returns true for a string which has only ASCII characters.

"abc".force_encoding("UTF-8").ascii_only?          #=> true
"abc\u{6666}".force_encoding("UTF-8").ascii_only?  #=> false

Returns:

  • (Boolean)

Returns:

  • (Boolean)
  • (Boolean)

- (String) bytes {|fixnum| ... } - (Enumerator) bytes

str.each_byte {|fixnum| block } -> str

str.each_byte                      -> an_enumerator

Passes each byte in str to the given block, or returns an enumerator if no block is given.

"hello".each_byte {|c| print c, ' ' }

produces:

104 101 108 108 111

Overloads:

  • - bytes {|fixnum| ... }

    Yields:

    • (fixnum)

    Returns:

  • - bytes

    Returns:

- (Integer) bytesize

Returns the length of str in bytes.

Returns:

- (String) capitalize

Returns a copy of str with the first character converted to uppercase and the remainder to lowercase. Note: case conversion is effective only in ASCII region.

"hello".capitalize    #=> "Hello"
"HELLO".capitalize    #=> "Hello"
"123ABC".capitalize   #=> "123abc"

Returns:

- (String?) capitalize!

Modifies str by converting the first character to uppercase and the remainder to lowercase. Returns nil if no changes are made. Note: case conversion is effective only in ASCII region.

a = "hello"
a.capitalize!   #=> "Hello"
a               #=> "Hello"
a.capitalize!   #=> nil

Returns:

- (-1, ...) casecmp(other_str)

Case-insensitive version of String#.

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

Returns:

  • (-1, 0, +1, nil)

- (String) center(integer, padstr)

If integer is greater than the length of str, returns a new String of length integer with str centered and padded with padstr; otherwise, returns str.

"hello".center(4)         #=> "hello"
"hello".center(20)        #=> "       hello        "
"hello".center(20, '123') #=> "1231231hello12312312"

Returns:

- (String) chars {|cstr| ... } - (Enumerator) chars

str.each_char {|cstr| block } -> str

str.each_char                    -> an_enumerator

Passes each character in str to the given block, or returns an enumerator if no block is given.

"hello".each_char {|c| print c, ' ' }

produces:

h e l l o

Overloads:

  • - chars {|cstr| ... }

    Yields:

    • (cstr)

    Returns:

  • - chars

    Returns:

- (String) chomp(separator = $/)

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:

- (String?) chomp!(separator = $/)

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

Returns:

- (String) chop

Returns a new String with the last character removed. If the string ends with \r\n, both characters are removed. Applying chop to an empty string returns an empty string. String#chomp is often a safer alternative, as it leaves the string unchanged if it doesn't end in a record separator.

"string\r\n".chop   #=> "string"
"string\n\r".chop   #=> "string\n"
"string\n".chop     #=> "string"
"string".chop       #=> "strin"
"x".chop.chop       #=> ""

Returns:

- (String?) chop!

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

Returns:

- (String) chr

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

a = "abcde"
a.chr    #=> "a"

Returns:

- (String) clear

Makes string empty.

a = "abcde"
a.clear    #=> ""

Returns:

- (String) codepoints {|integer| ... } - (Enumerator) codepoints

str.each_codepoint {|integer| block } -> str

str.each_codepoint                       -> an_enumerator

Passes the Integer ordinal of each character in str, also known as a codepoint when applied to Unicode strings to the given block.

If no block is given, an enumerator is returned instead.

"hello\u0639".each_codepoint {|c| print c, ' ' }

produces:

104 101 108 108 111 1593

Overloads:

  • - codepoints {|integer| ... }

    Yields:

    • (integer)

    Returns:

  • - codepoints

    Returns:

- (String) <<(integer) - (String) concat(integer) - (String) <<(obj) - (String) concat(obj)

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:

- (Fixnum) count([other_str])

Each other_str parameter defines a set of characters to count. The intersection of these sets defines the characters to count in str. Any other_str that starts with a caret (^) is negated. The sequence c1--c2 means all characters between c1 and c2.

a = "hello world"
a.count "lo"            #=> 5
a.count "lo", "o"       #=> 2
a.count "hello", "^l"   #=> 4
a.count "ej-m"          #=> 4

Returns:

- (String) crypt(other_str)

Applies a one-way cryptographic hash to str by invoking the standard library function crypt. The argument is the salt string, which should be two characters long, each character drawn from [a-zA-Z0-9./].

Returns:

- (String) delete([other_str])

Returns a copy of str with all characters in the intersection of its arguments deleted. Uses the same rules for building the set of characters as String#count.

"hello".delete "l","lo"        #=> "heo"
"hello".delete "lo"            #=> "he"
"hello".delete "aeiou", "^e"   #=> "hell"
"hello".delete "ej-m"          #=> "ho"

Returns:

- (String?) delete!([other_str])

Performs a delete operation in place, returning str, or nil if str was not modified.

Returns:

- (String) downcase

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. Note: case replacement is effective only in ASCII region.

"hEllO".downcase   #=> "hello"

Returns:

- (String?) downcase!

Downcases the contents of str, returning nil if no changes were made. Note: case replacement is effective only in ASCII region.

Returns:

- (String) dump

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

Returns:

- (Object) dup

:nodoc:

- (String) bytes {|fixnum| ... } - (Enumerator) bytes

str.each_byte {|fixnum| block } -> str

str.each_byte                      -> an_enumerator

Passes each byte in str to the given block, or returns an enumerator if no block is given.

"hello".each_byte {|c| print c, ' ' }

produces:

104 101 108 108 111

Overloads:

  • - bytes {|fixnum| ... }

    Yields:

    • (fixnum)

    Returns:

  • - bytes

    Returns:

- (String) chars {|cstr| ... } - (Enumerator) chars

str.each_char {|cstr| block } -> str

str.each_char                    -> an_enumerator

Passes each character in str to the given block, or returns an enumerator if no block is given.

"hello".each_char {|c| print c, ' ' }

produces:

h e l l o

Overloads:

  • - chars {|cstr| ... }

    Yields:

    • (cstr)

    Returns:

  • - chars

    Returns:

- (String) codepoints {|integer| ... } - (Enumerator) codepoints

str.each_codepoint {|integer| block } -> str

str.each_codepoint                       -> an_enumerator

Passes the Integer ordinal of each character in str, also known as a codepoint when applied to Unicode strings to the given block.

If no block is given, an enumerator is returned instead.

"hello\u0639".each_codepoint {|c| print c, ' ' }

produces:

104 101 108 108 111 1593

Overloads:

  • - codepoints {|integer| ... }

    Yields:

    • (integer)

    Returns:

  • - codepoints

    Returns:

- (String) each_line(separator = $/) {|substr| ... } - (Enumerator) each_line(separator = $/)

str.lines(separator=$/) {|substr| block } -> str

str.lines(separator=$/)                         -> an_enumerator

Splits str using the supplied parameter as the record separator ($/ by default), passing each substring in turn to the supplied block. If a zero-length record separator is supplied, the string is split into paragraphs delimited by multiple successive newlines.

If no block is given, an enumerator is returned instead.

print "Example one\n"
"hello\nworld".each_line {|s| p s}
print "Example two\n"
"hello\nworld".each_line('l') {|s| p s}
print "Example three\n"
"hello\n\n\nworld".each_line('') {|s| p s}

produces:

Example one
"hello\n"
"world"
Example two
"hel"
"l"
"o\nworl"
"d"
Example three
"hello\n\n\n"
"world"

Overloads:

  • - each_line {|substr| ... }

    Yields:

    • (substr)

    Returns:

  • - each_line

    Returns:

- (Boolean) empty?

Returns true if str has a length of zero.

"hello".empty?   #=> false
"".empty?        #=> true

Returns:

  • (Boolean)

Returns:

  • (Boolean)

- (String) encode!(encoding[, options]) - (String) encode!(dst_encoding, src_encoding[, options])

The first form transcodes the contents of str from str.encoding to encoding. The second form transcodes the contents of str from src_encoding to dst_encoding. The options Hash gives details for conversion. See String#encode for details. Returns the string even if no changes were made.

Overloads:

- (Encoding) encoding

Returns the Encoding object that represents the encoding of obj.

Returns:

- (Boolean) end_with?([suffix])

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

Returns:

  • (Boolean)

Returns:

  • (Boolean)

- (Boolean) ==(obj)

Equality---If obj is not a String, returns false. Otherwise, returns true if str obj returns zero.

Returns:

  • (Boolean)

Returns:

  • (Boolean)

- (String) force_encoding(encoding)

Changes the encoding to encoding and returns self.

Returns:

- (0 .. 255) getbyte(index)

returns the indexth byte as an integer.

Returns:

  • (0 .. 255)

- (String) gsub(pattern, replacement) - (String) gsub(pattern, hash) - (String) gsub(pattern) {|match| ... } - (Enumerator) gsub(pattern)

Returns a copy of str with the all occurrences of pattern substituted for the second argument. The pattern is typically a Regexp; if given as a String, any regular expression metacharacters it contains will be interpreted literally, e.g. '\\d' will match a backlash followed by 'd', instead of a digit.

If replacement is a String it will be substituted for the matched text. It may contain back-references to the pattern's capture groups of the form \\d, where d is a group number, or \\k, where n is a group name. If it is a double-quoted string, both back-references must be preceded by an additional backslash. However, within replacement the special match variables, such as &$, will not refer to the current match.

If the second argument is a Hash, and the matched text is one of its keys, the corresponding value is the replacement string.

In the block form, the current match string is passed in as a parameter, and variables such as $1, $2, $`, $&, and $' will be set appropriately. The value returned by the block will be substituted for the match on each call.

The result inherits any tainting in the original string or any supplied replacement string.

When neither a block nor a second argument is supplied, an Enumerator is returned.

"hello".gsub(/[aeiou]/, '*')                  #=> "h*ll*"
"hello".gsub(/([aeiou])/, '<\1>')             #=> "h<e>ll<o>"
"hello".gsub(/./) {|s| s.ord.to_s + ' '}      #=> "104 101 108 108 111 "
"hello".gsub(/(?<foo>[aeiou])/, '{\k<foo>}')  #=> "h{e}ll{o}"
'hello'.gsub(/[eo]/, 'e' => 3, 'o' => '*')    #=> "h3ll*"

Overloads:

- (String?) gsub!(pattern, replacement) - (String?) gsub!(pattern) {|match| ... } - (Enumerator) gsub!(pattern)

Performs the substitutions of String#gsub in place, returning str, or nil if no substitutions were performed. If no block and no replacement is given, an enumerator is returned instead.

Overloads:

  • - gsub!

    Returns:

  • - gsub! {|match| ... }

    Yields:

    • (match)

    Returns:

  • - gsub!

    Returns:

- (Integer) hex

Treats leading characters from str as a string of hexadecimal digits (with an optional sign and an optional 0x) and returns the corresponding number. Zero is returned on error.

"0x0a".hex     #=> 10
"-1234".hex    #=> -4660
"0".hex        #=> 0
"wombat".hex   #=> 0

Returns:

- (Boolean) include?(other_str)

Returns true if str contains the given string or character.

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

Returns:

  • (Boolean)

Returns:

  • (Boolean)

- (Fixnum?) index(substring[, offset]) - (Fixnum?) index(regexp[, offset])

Returns the index of the first occurrence of the given substring or pattern (regexp) in str. Returns nil if not found. If the second parameter is present, it specifies the position in the string to begin the search.

"hello".index('e')             #=> 1
"hello".index('lo')            #=> 3
"hello".index('a')             #=> nil
"hello".index(?e)              #=> 1
"hello".index(/[aeiou]/, -3)   #=> 4

Overloads:

  • - index

    Returns:

  • - index

    Returns:

- (String) replace(other_str)

Replaces the contents and taintedness of str with the corresponding values in other_str.

s = "hello"         #=> "hello"
s.replace "world"   #=> "world"

Returns:

- (String) insert(index, other_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"

Returns:

- (String) inspect

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

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

Returns:

- (Symbol) intern - (Symbol) to_sym

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"

Overloads:

- (String) each_line(separator = $/) {|substr| ... } - (Enumerator) each_line(separator = $/)

str.lines(separator=$/) {|substr| block } -> str

str.lines(separator=$/)                         -> an_enumerator

Splits str using the supplied parameter as the record separator ($/ by default), passing each substring in turn to the supplied block. If a zero-length record separator is supplied, the string is split into paragraphs delimited by multiple successive newlines.

If no block is given, an enumerator is returned instead.

print "Example one\n"
"hello\nworld".each_line {|s| p s}
print "Example two\n"
"hello\nworld".each_line('l') {|s| p s}
print "Example three\n"
"hello\n\n\nworld".each_line('') {|s| p s}

produces:

Example one
"hello\n"
"world"
Example two
"hel"
"l"
"o\nworl"
"d"
Example three
"hello\n\n\n"
"world"

Overloads:

  • - each_line {|substr| ... }

    Yields:

    • (substr)

    Returns:

  • - each_line

    Returns:

- (String) ljust(integer, padstr = ' ')

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"

Returns:

- (String) lstrip

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

"  hello  ".lstrip   #=> "hello  "
"hello".lstrip       #=> "hello"

Returns:

- (self?) lstrip!

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

Returns:

  • (self, nil)

- (MatchData?) match(pattern) - (MatchData?) match(pattern, pos)

Converts pattern to a Regexp (if it isn't already one), then invokes its match method on str. If the second parameter is present, it specifies the position in the string to begin the search.

'hello'.match('(.)\1')      #=> #<MatchData "ll" 1:"l">
'hello'.match('(.)\1')[0]   #=> "ll"
'hello'.match(/(.)\1/)[0]   #=> "ll"
'hello'.match('xx')         #=> nil

If a block is given, invoke the block with MatchData if match succeed, so that you can write

str.match(pat) {|m| ...}

instead of

if m = str.match(pat)
  ...
end

The return value is a value from block execution in this case.

Overloads:

- (String) succ - (String) next

Returns the successor to str. The successor is calculated by incrementing characters starting from the rightmost alphanumeric (or the rightmost character if there are no alphanumerics) in the string. Incrementing a digit always results in another digit, and incrementing a letter results in another letter of the same case. Incrementing nonalphanumerics uses the underlying character set's collating sequence.

If the increment generates a "carry," the character to the left of it is incremented. This process repeats until there is no carry, adding an additional character if necessary.

"abcd".succ        #=> "abce"
"THX1138".succ     #=> "THX1139"
"<<koala>>".succ   #=> "<<koalb>>"
"1999zzz".succ     #=> "2000aaa"
"ZZZ9999".succ     #=> "AAAA0000"
"***".succ         #=> "**+"

Overloads:

- (String) succ! - (String) next!

Equivalent to String#succ, but modifies the receiver in place.

Overloads:

- (Integer) oct

Treats leading characters of str as a string of octal digits (with an optional sign) and returns the corresponding number. Returns 0 if the conversion fails.

"123".oct       #=> 83
"-377".oct      #=> -255
"bad".oct       #=> 0
"0377bad".oct   #=> 255

Returns:

- (Integer) ord

Return the Integer ordinal of a one-character string.

"a".ord         #=> 97

Returns:

- (Array) partition(sep) - (Array) partition(regexp)

Searches sep or pattern (regexp) in the string and returns the part before it, the match, and the part after it. If it is not found, returns two empty strings and str.

"hello".partition("l")         #=> ["he", "l", "lo"]
"hello".partition("x")         #=> ["hello", "", ""]
"hello".partition(/.l/)        #=> ["h", "el", "lo"]

Overloads:

  • - partition

    Returns:

  • - partition

    Returns:

- (Pointer) pointer

returns a Pointer object wrapping the receiver's internal storage (be very careful, changing the pointer will change the original string's content!).

Returns:

- (String) replace(other_str)

Replaces the contents and taintedness of str with the corresponding values in other_str.

s = "hello"         #=> "hello"
s.replace "world"   #=> "world"

Returns:

- (String) reverse

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

"stressed".reverse   #=> "desserts"

Returns:

- (String) reverse!

Reverses str in place.

Returns:

- (Fixnum?) rindex(substring[, fixnum]) - (Fixnum?) rindex(regexp[, fixnum])

Returns the index of the last occurrence of the given substring or pattern (regexp) in str. Returns nil if not found. If the second parameter is present, it specifies the position in the string to end the search---characters beyond this point will not be considered.

"hello".rindex('e')             #=> 1
"hello".rindex('l')             #=> 3
"hello".rindex('a')             #=> nil
"hello".rindex(?e)              #=> 1
"hello".rindex(/[aeiou]/, -2)   #=> 1

Overloads:

  • - rindex

    Returns:

  • - rindex

    Returns:

- (String) rjust(integer, padstr = ' ')

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"

Returns:

- (Array) rpartition(sep) - (Array) rpartition(regexp)

Searches sep or pattern (regexp) in the string from the end of the string, and returns the part before it, the match, and the part after it. If it is not found, returns two empty strings and str.

"hello".rpartition("l")         #=> ["hel", "l", "o"]
"hello".rpartition("x")         #=> ["", "", "hello"]
"hello".rpartition(/.l/)        #=> ["he", "ll", "o"]

Overloads:

  • - rpartition

    Returns:

  • - rpartition

    Returns:

- (String) rstrip

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

"  hello  ".rstrip   #=> "  hello"
"hello".rstrip       #=> "hello"

Returns:

- (self?) rstrip!

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

Returns:

  • (self, nil)

- (Array) scan(pattern) - (String) scan(pattern) {|match, ...| ... }

Both forms iterate through str, matching the pattern (which may be a Regexp or a String). For each match, a result is generated and either added to the result array or passed to the block. If the pattern contains no groups, each individual result consists of the matched string, $&. If the pattern contains groups, each individual result is itself an array containing one entry per group.

a = "cruel world"
a.scan(/\w+/)        #=> ["cruel", "world"]
a.scan(/.../)        #=> ["cru", "el ", "wor"]
a.scan(/(...)/)      #=> [["cru"], ["el "], ["wor"]]
a.scan(/(..)(..)/)   #=> [["cr", "ue"], ["l ", "wo"]]

And the block form:

a.scan(/\w+/) {|w| print "<<#{w}>> " }
print "\n"
a.scan(/(.)(.)/) {|x,y| print y, x }
print "\n"

produces:

"rceu lowlr\n">> "">>

Overloads:

  • - scan

    Returns:

  • - scan {|match, ...| ... }

    Yields:

    • (match, ...)

    Returns:

- (Integer) setbyte(index, int)

modifies the indexth byte as int.

Returns:

- (Integer) length - (Integer) size

Returns the character length of str.

Overloads:

- (String?) [](fixnum) - (String?) [](fixnum, fixnum) - (String?) [](range) - (String?) [](regexp) - (String?) [](regexp, fixnum) - (String?) [](other_str) - (String?) slice(fixnum) - (String?) slice(fixnum, fixnum) - (String?) slice(range) - (String?) slice(regexp) - (String?) slice(regexp, fixnum) - (String?) slice(regexp, capname) - (String?) slice(other_str)

Element Reference---If passed a single Fixnum, returns a substring of one character at that position. If passed two Fixnum objects, returns a substring starting at the offset given by the first, and with a length given by the second. If passed a range, its beginning and end are interpreted as offsets delimiting the substring to be 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 or the length is negative.

If a Regexp is supplied, the matching portion of str is returned. If a numeric or name parameter follows the regular expression, that component of the MatchData is returned instead. 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]                   #=> "e"
a[2, 3]                #=> "llo"
a[2..3]                #=> "ll"
a[-3, 2]               #=> "er"
a[7..-2]               #=> "her"
a[-4..-2]              #=> "her"
a[-2..-4]              #=> ""
a[12..-1]              #=> nil
a[/[aeiou](.)\1/]      #=> "ell"
a[/[aeiou](.)\1/, 0]   #=> "ell"
a[/[aeiou](.)\1/, 1]   #=> "l"
a[/[aeiou](.)\1/, 2]   #=> nil
a["lo"]                #=> "lo"
a["bye"]               #=> nil

Overloads:

- (Fixnum?) slice!(fixnum) - (String?) slice!(fixnum, fixnum) - (String?) slice!(range) - (String?) slice!(regexp) - (String?) slice!(other_str)

Deletes the specified portion from str, and returns the portion deleted.

string = "this is a string"
string.slice!(2)        #=> "i"
string.slice!(3..6)     #=> " is "
string.slice!(/s.*t/)   #=> "sa st"
string.slice!("r")      #=> "r"
string                  #=> "thing"

Overloads:

  • - slice!

    Returns:

  • - slice!

    Returns:

  • - slice!

    Returns:

  • - slice!

    Returns:

  • - slice!

    Returns:

- (Array) split(pattern = $;, [limit])

Divides str into substrings based on a delimiter, returning an array of these substrings.

If pattern is a String, then its contents are used as the delimiter when splitting str. If pattern is a single space, str is split on whitespace, with leading whitespace and runs of contiguous whitespace characters ignored.

If pattern is a Regexp, str is divided where the pattern matches. Whenever the pattern matches a zero-length string, str is split into individual characters. If pattern contains groups, the respective matches will be returned in the array as well.

If pattern is 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"]
"1, 2.34,56, 7".split(%r{,\s*}) #=> ["1", "2.34", "56", "7"]
"hello".split(//)               #=> ["h", "e", "l", "l", "o"]
"hello".split(//, 3)            #=> ["h", "e", "llo"]
"hi mom".split(%r{\s*})         #=> ["h", "i", "m", "o", "m"]

"mellow yellow".split("ello")   #=> ["m", "w y", "w"]
"1,2,,3,4,,".split(',')         #=> ["1", "2", "", "3", "4"]
"1,2,,3,4,,".split(',', 4)      #=> ["1", "2", "", "3,4,,"]
"1,2,,3,4,,".split(',', -4)     #=> ["1", "2", "", "3", "4", "", ""]

Returns:

- (String) squeeze([other_str])

Builds a set of characters from the other_str parameter(s) using the procedure described for String#count. Returns a new string where runs of the same character that occur in this set are replaced by a single character. If no arguments are given, all runs of identical characters are replaced by a single character.

"yellow moon".squeeze                  #=> "yelow mon"
"  now   is  the".squeeze(" ")         #=> " now is the"
"putters shoot balls".squeeze("m-z")   #=> "puters shot balls"

Returns:

- (String?) squeeze!([other_str])

Squeezes str in place, returning either str, or nil if no changes were made.

Returns:

- (Boolean) start_with?([prefix])

Returns true if str starts with one of the prefixes given.

p "hello".start_with?("hell")               #=> true

# returns true if one of the prefixes matches.
p "hello".start_with?("heaven", "hell")     #=> true
p "hello".start_with?("heaven", "paradise") #=> false

Returns:

  • (Boolean)

Returns:

  • (Boolean)

- (String) strip

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

"    hello    ".strip   #=> "hello"
"\tgoodbye\r\n".strip   #=> "goodbye"

Returns:

- (String?) strip!

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

Returns:

- (String) sub(pattern, replacement) - (String) sub(pattern, hash) - (String) sub(pattern) {|match| ... }

Returns a copy of str with the first occurrence of pattern substituted for the second argument. The pattern is typically a Regexp; if given as a String, any regular expression metacharacters it contains will be interpreted literally, e.g. '\\d' will match a backlash followed by 'd', instead of a digit.

If replacement is a String it will be substituted for the matched text. It may contain back-references to the pattern's capture groups of the form \\d, where d is a group number, or \\k, where n is a group name. If it is a double-quoted string, both back-references must be preceded by an additional backslash. However, within replacement the special match variables, such as &$, will not refer to the current match.

If the second argument is a Hash, and the matched text is one of its keys, the corresponding value is the replacement string.

In the block form, the current match string is passed in as a parameter, and variables such as $1, $2, $`, $&, and $' will be set appropriately. The value returned by the block will be substituted for the match on each call.

The result inherits any tainting in the original string or any supplied replacement string.

"hello".sub(/[aeiou]/, '*')                  #=> "h*llo"
"hello".sub(/([aeiou])/, '<\1>')             #=> "h<e>llo"
"hello".sub(/./) {|s| s.ord.to_s + ' ' }     #=> "104 ello"
"hello".sub(/(?<foo>[aeiou])/, '*\k<foo>*')  #=> "h*e*llo"
'Is SHELL your preferred shell?'.sub(/[[:upper:]]{2,}/, ENV)
 #=> "Is /bin/bash your preferred shell?"

Overloads:

  • - sub

    Returns:

  • - sub

    Returns:

  • - sub {|match| ... }

    Yields:

    • (match)

    Returns:

- (String?) sub!(pattern, replacement) - (String?) sub!(pattern) {|match| ... }

Performs the substitutions of String#sub in place, returning str, or nil if no substitutions were performed.

Overloads:

  • - sub!

    Returns:

  • - sub! {|match| ... }

    Yields:

    • (match)

    Returns:

- (String) succ - (String) next

Returns the successor to str. The successor is calculated by incrementing characters starting from the rightmost alphanumeric (or the rightmost character if there are no alphanumerics) in the string. Incrementing a digit always results in another digit, and incrementing a letter results in another letter of the same case. Incrementing nonalphanumerics uses the underlying character set's collating sequence.

If the increment generates a "carry," the character to the left of it is incremented. This process repeats until there is no carry, adding an additional character if necessary.

"abcd".succ        #=> "abce"
"THX1138".succ     #=> "THX1139"
"<<koala>>".succ   #=> "<<koalb>>"
"1999zzz".succ     #=> "2000aaa"
"ZZZ9999".succ     #=> "AAAA0000"
"***".succ         #=> "**+"

Overloads:

- (String) succ! - (String) next!

Equivalent to String#succ, but modifies the receiver in place.

Overloads:

- (Integer) sum(n = 16)

Returns a basic n-bit checksum of the characters in str, where n is the optional Fixnum parameter, defaulting to 16. The result is simply the sum of the binary value of each character in str modulo 2**n - 1. This is not a particularly good checksum.

Returns:

- (String) swapcase

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:

- (String?) swapcase!

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:

- (Object) to_c

Returns a complex which denotes the string form. The parser ignores leading whitespaces and trailing garbage. Any digit sequences can be separated by an underscore. Returns zero for null or garbage string.

For example:

'9'.to_c           #=> (9+0i)
'2.5'.to_c         #=> (2.5+0i)
'2.5/1'.to_c       #=> ((5/2)+0i)
'-3/2'.to_c        #=> ((-3/2)+0i)
'-i'.to_c          #=> (0-1i)
'45i'.to_c         #=> (0+45i)
'3-4i'.to_c        #=> (3-4i)
'-4e2-4e-2i'.to_c  #=> (-400.0-0.04i)
'-0.0-0.0i'.to_c   #=> (-0.0-0.0i)
'1/2+3/4i'.to_c    #=> ((1/2)+(3/4)*i)
'ruby'.to_c        #=> (0+0i)

- (NSData) to_data

returns an NSData object wrapping the receiver's internal storage.

Returns:

- (Float) to_f

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:

- (Integer) to_i(base = 10)

Returns the result of interpreting leading characters in str as an integer base base (between 2 and 36). Extraneous characters past the end of a valid number are ignored. If there is not a valid number at the start of str, 0 is returned. This method never raises an exception when base is valid.

"12345".to_i             #=> 12345
"99 red balloons".to_i   #=> 99
"0a".to_i                #=> 0
"0a".to_i(16)            #=> 10
"hello".to_i             #=> 0
"1100101".to_i(2)        #=> 101
"1100101".to_i(8)        #=> 294977
"1100101".to_i(10)       #=> 1100101
"1100101".to_i(16)       #=> 17826049

Returns:

- (Rational) to_r

Returns a rational which denotes the string form. The parser ignores leading whitespaces and trailing garbage. Any digit sequences can be separated by an underscore. Returns zero for null or garbage string.

NOTE: '0.3'.to_r isn't the same as 0.3.to_r. The former is equivalent to '3/10'.to_r, but the latter isn't so.

For example:

'  2  '.to_r       #=> (2/1)
'300/2'.to_r       #=> (150/1)
'-9.2'.to_r        #=> (-46/5)
'-9.2e2'.to_r      #=> (-920/1)
'1_234_567'.to_r   #=> (1234567/1)
'21 june 09'.to_r  #=> (21/1)
'21/06/09'.to_r    #=> (7/2)
'bwv 1079'.to_r    #=> (0/1)

Returns:

- (String) to_s - (String) to_str

Returns the receiver.

Overloads:

- (String) to_s - (String) to_str

Returns the receiver.

Overloads:

- (Symbol) intern - (Symbol) to_sym

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"

Overloads:

- (String) tr(from_str, to_str)

Returns a copy of str with the characters in from_str replaced by the corresponding characters in to_str. If to_str is shorter than from_str, it is padded with its last character in order to maintain the correspondence.

"hello".tr('el', 'ip')      #=> "hippo"
"hello".tr('aeiou', '*')    #=> "h*ll*"

Both strings may use the c1-c2 notation to denote ranges of characters, and from_str may start with a ^, which denotes all characters except those listed.

"hello".tr('a-y', 'b-z')    #=> "ifmmp"
"hello".tr('^aeiou', '*')   #=> "*e**o"

Returns:

- (String?) tr!(from_str, to_str)

Translates str in place, using the same rules as String#tr. Returns str, or nil if no changes were made.

Returns:

- (String) tr_s(from_str, to_str)

Processes a copy of str as described under String#tr, then removes duplicate characters in regions that were affected by the translation.

"hello".tr_s('l', 'r')     #=> "hero"
"hello".tr_s('el', '*')    #=> "h*o"
"hello".tr_s('el', 'hx')   #=> "hhxo"

Returns:

- (String?) tr_s!(from_str, to_str)

Performs String#tr_s processing on str in place, returning str, or nil if no changes were made.

Returns:

- (String) transform(pattern)

Returns a new String which is transformed to uppercase/lowercase or another language characters. This method is implemented with ICU Transforms. Refer to userguide.icu-project.org/transforms/general to consider transform pattern.

Returns:

- (Array) unpack(format)

Decodes str (which may contain binary data) according to the format string, returning an array of each value extracted. The format string consists of a sequence of single-character directives, summarized in the table at the end of this entry. Each directive may be followed by a number, indicating the number of times to repeat with this directive. An asterisk ("*") will use up all remaining elements. The directives sSiIlL may each be followed by an underscore ("_") or exclamation mark ("!") to use the underlying platform's native size for the specified type; otherwise, it uses a platform-independent consistent size. Spaces are ignored in the format string. See also Array#pack.

"abc \0\0abc \0\0".unpack('A6Z6')   #=> ["abc", "abc "]
"abc \0\0".unpack('a3a3')           #=> ["abc", " \000\000"]
"abc \0abc \0".unpack('Z*Z*')       #=> ["abc ", "abc "]
"aa".unpack('b8B8')                 #=> ["10000110", "01100001"]
"aaa".unpack('h2H2c')               #=> ["16", "61", 97]
"\xfe\xff\xfe\xff".unpack('sS')     #=> [-2, 65534]
"now=20is".unpack('M*')             #=> ["now is"]
"whole".unpack('xax2aX2aX1aX2a')    #=> ["h", "e", "l", "l", "o"]

This table summarizes the various formats and the Ruby classes returned by each.

Integer      |         |
Directive    | Returns | Meaning
-----------------------------------------------------------------
   C         | Integer | 8-bit unsigned (unsigned char)
   S         | Integer | 16-bit unsigned, native endian (uint16_t)
   L         | Integer | 32-bit unsigned, native endian (uint32_t)
   Q         | Integer | 64-bit unsigned, native endian (uint64_t)
             |         |
   c         | Integer | 8-bit signed (signed char)
   s         | Integer | 16-bit signed, native endian (int16_t)
   l         | Integer | 32-bit signed, native endian (int32_t)
   q         | Integer | 64-bit signed, native endian (int64_t)
             |         |
   S_, S!    | Integer | unsigned short, native endian
   I, I_, I! | Integer | unsigned int, native endian
   L_, L!    | Integer | unsigned long, native endian
             |         |
   s_, s!    | Integer | signed short, native endian
   i, i_, i! | Integer | signed int, native endian
   l_, l!    | Integer | signed long, native endian
             |         |
   S> L> Q>  | Integer | same as the directives without ">" except
   s> l> q>  |         | big endian
   S!> I!>   |         | (available since Ruby 1.9.3)
   L!> Q!>   |         | "S>" is same as "n"
   s!> i!>   |         | "L>" is same as "N"
   l!> q!>   |         |
             |         |
   S< L< Q<  | Integer | same as the directives without "<" except
   s< l< q<  |         | little endian
   S!< I!<   |         | (available since Ruby 1.9.3)
   L!< Q!<   |         | "S<" is same as "v"
   s!< i!<   |         | "L<" is same as "V"
   l!< q!<   |         |
             |         |
   n         | Integer | 16-bit unsigned, network (big-endian) byte order
   N         | Integer | 32-bit unsigned, network (big-endian) byte order
   v         | Integer | 16-bit unsigned, VAX (little-endian) byte order
   V         | Integer | 32-bit unsigned, VAX (little-endian) byte order
             |         |
   U         | Integer | UTF-8 character
   w         | Integer | BER-compressed integer (see Array.pack)

Float        |         |
Directive    | Returns | Meaning
-----------------------------------------------------------------
   D, d      | Float   | double-precision, native format
   F, f      | Float   | single-precision, native format
   E         | Float   | double-precision, little-endian byte order
   e         | Float   | single-precision, little-endian byte order
   G         | Float   | double-precision, network (big-endian) byte order
   g         | Float   | single-precision, network (big-endian) byte order

String       |         |
Directive    | Returns | Meaning
-----------------------------------------------------------------
   A         | String  | arbitrary binary string (remove trailing nulls and ASCII spaces)
   a         | String  | arbitrary binary string
   Z         | String  | null-terminated string
   B         | String  | bit string (MSB first)
   b         | String  | bit string (LSB first)
   H         | String  | hex string (high nibble first)
   h         | String  | hex string (low nibble first)
   u         | String  | UU-encoded string
   M         | String  | quoted-printable, MIME encoding (see RFC2045)
   m         | String  | base64 encoded string (RFC 2045) (default)
             |         | base64 encoded string (RFC 4648) if followed by 0
   P         | String  | pointer to a structure (fixed-length string)
   p         | String  | pointer to a null-terminated string

Misc.        |         |
Directive    | Returns | Meaning
-----------------------------------------------------------------
   @         | ---     | skip to the offset given by the length argument
   X         | ---     | skip backward one byte
   x         | ---     | skip forward one byte

Returns:

- (String) upcase

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. Note: case replacement is effective only in ASCII region.

"hEllO".upcase   #=> "HELLO"

Returns:

- (String?) upcase!

Upcases the contents of str, returning nil if no changes were made. Note: case replacement is effective only in ASCII region.

Returns:

- (String) upto(other_str, exclusive = false) {|s| ... } - (Enumerator) upto(other_str, exclusive = false)

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:

- (Boolean) valid_encoding?

Returns true for a string which encoded correctly.

"\xc2\xa1".force_encoding("UTF-8").valid_encoding?  #=> true
"\xc2".force_encoding("UTF-8").valid_encoding?      #=> false
"\x80".force_encoding("UTF-8").valid_encoding?      #=> false

Returns:

  • (Boolean)

Returns:

  • (Boolean)
  • (Boolean)