String Flashcards

You may prefer our related Brainscape-certified flashcards:
1
Q

What are String objects?

A

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#[ ]=.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

new

A

new(str=””) → new_str

Returns a new string object containing a copy of str.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

try_convert

A

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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

%

A

str % arg → new_str

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"
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

*

A

str * integer → new_str
Copy — Returns a new String containing integer copies of the receiver. integer must be greater than or equal to 0.

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

+

A

str + other_str → new_str
Concatenation—Returns a new String containing other_str concatenated to str.

“Hello from “ + self.to_s #=> “Hello from main”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

«

A

str &laquo_space;integer → str
str &laquo_space;obj → str
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 &laquo_space;“world” #=> “hello world”
a.concat(33) #=> “hello world!”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q
A

string other_string → -1, 0, +1 or nil
Comparison—Returns -1, 0, +1 or nil depending on whether string is less than, equal to, or greater than other_string.

nil is returned if the two values are incomparable.

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.

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

==

A

str == obj → true or false
Equality¶ ↑

Returns whether str == obj, similar to Object#==.

If obj is not an instance of String but responds to to_str, then the two strings are compared using case equality Object#===.

Otherwise, returns similarly to #eql?, comparing length and content.

Supplemental notes

These two methods, == and ===, share the same implementation.

A good explanation for this was provided by Jacob Bandes-Storch on Stack Exchange: http://stackoverflow.com/questions/7156955/whats-the-difference-between-equal-eql-and

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

===

A

str === obj → true or false
Equality - Returns whether str == obj, similar to Object#==.

If obj is not an instance of String but responds to to_str, then the two strings are compared using case equality Object#===.

Otherwise, returns similarly to #eql?, comparing length and content.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

=~

A

str =~ obj → fixnum or nil
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.

Note: str =~ regexp is not the same as regexp =~ str. Strings captured from named capture groups are assigned to local variables only in the second case.

“cat o’ 9 tails” =~ /\d/ #=> 7
“cat o’ 9 tails” =~ 9 #=> nil

In this example …

“cat o’ 9 tails” =~ /\d/ #=> 7

… note that the regular expression /\d/ will match any single digit. What is returned is not the matched digit, but the zero-based location of that digit. The “9” is the eighth character in the string, so, counting from zero, the match returns the integer 7.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

[]

A
str[index] → new_str or nil 
str[start, length] → new_str or nil
str[range] → new_str or nil
str[regexp] → new_str or nil
str[regexp, capture] → new_str or nil
str[match_str] → new_str or nil
Element Reference — If passed a single index, returns a substring of one character at that index. If passed a start index and a length, returns a substring containing length characters starting at the index. If passed a range, its beginning and end are interpreted as offsets delimiting the substring to be returned.

In these three cases, if an index is negative, it is counted from the end of the string. For the start and range cases the starting index is just before a character and an index matching the string’s size. Additionally, an empty string is returned when the starting index for a character range is at the end of the string.

Returns nil if the initial index falls outside the string or the length is negative.

If a Regexp is supplied, the matching portion of the string is returned. If a capture follows the regular expression, which may be a capture group index or name, follows the regular expression that component of the MatchData is returned instead.

If a match_str is given, that string is returned if it occurs in the string.

Returns nil if the regular expression does not match or the match string cannot be found.

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[11, 0] #=> “”
a[11] #=> nil
a[12, 0] #=> nil
a[12..-1] #=> nil

a[/aeiou\1/] #=> “ell”
a[/aeiou\1/, 0] #=> “ell”
a[/aeiou\1/, 1] #=> “l”
a[/aeiou\1/, 2] #=> nil

a[/(?[aeiou])(?[^aeiou])/, “non_vowel”] #=> “l”
a[/(?[aeiou])(?[^aeiou])/, “vowel”] #=> “e”

a[“lo”] #=> “lo”
a[“bye”] #=> nil

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

[]=

A
str[fixnum] = new_str
str[fixnum, fixnum] = new_str
str[range] = aString
str[regexp] = new_str
str[regexp, fixnum] = new_str
str[regexp, name] = new_str
str[other_str] = new_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 will raise an IndexError on negative match.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

ascii_only?

A

ascii_only? → true or false
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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

b

A

b → str

Returns a copied string whose encoding is ASCII-8BIT.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

bytes

A

bytes → an_array
Returns an array of bytes in str. This is a shorthand for str.each_byte.to_a.

If a block is given, which is a deprecated form, works the same as each_byte.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

bytesize

A

bytesize → integer
Returns the length of str in bytes.

“\x80\u3042”.bytesize #=> 4
“hello”.bytesize #=> 5

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

byteslice

A

byteslice(fixnum) → new_str or nil
byteslice(fixnum, fixnum) → new_str or nil
byteslice(range) → new_str or nil
Byte Reference—If passed a single Fixnum, returns a substring of one byte 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 bytes 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. The encoding of the resulted string keeps original encoding.

“hello”.byteslice(1) #=> “e”
“hello”.byteslice(-1) #=> “o”
“hello”.byteslice(1, 2) #=> “el”
“\x80\u3042”.byteslice(1, 3) #=> “\u3042”
“\x03\u3042\xff”.byteslice(1..3) #=> “\u3042”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

capitalize

A

capitalize → new_str
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”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

capitalize!

A

capitalize! → str or nil
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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

casecmp

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

center

A

center(width, padstr=’ ‘) → new_str
Centers str in width. If width is greater than the length of str, returns a new String of length width with str centered and padded with padstr; otherwise, returns str.

“hello”.center(4) #=> “hello”
“hello”.center(20) #=> “ hello “
“hello”.center(20, ‘123’) #=> “1231231hello12312312”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

chars

A

chars → an_array
Returns an array of characters in str. This is a shorthand for str.each_char.to_a.

If a block is given, which is a deprecated form, works the same as each_char.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

chomp

A

chomp(separator=$/) → new_str
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"
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

chomp!

A

chomp!(separator=$/) → str or nil

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

chop

A

chop → new_str
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       #=> ""
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

chop!

A

chop! → str or nil

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

chr

A

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

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

clear

A

clear → string

Makes string empty.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

codepoints

A

codepoints → an_array
Returns an array of the Integer ordinals of the characters in str. This is a shorthand for str.each_codepoint.to_a.

If a block is given, which is a deprecated form, works the same as each_codepoint.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

concat

A

concat(integer) → str
concat(obj) → str
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 &laquo_space;“world” #=> “hello world”
a.concat(33) #=> “hello world!”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
32
Q

count

A

count([other_str]+) → fixnum
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. The backslash character </code> can be used to escape <code>^ or - and is otherwise ignored unless it appears at the end of a sequence or the end of a other_str.</code>

a = “hello world”

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

“hello^world”.count “\^aeiou” #=> 4
“hello-world”.count “a\-eo” #=> 4

c = “hello world\r\n”

c. count “\” #=> 2
c. count “\A” #=> 0
c. count “X-\w” #=> 3

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
33
Q

crypt

A

crypt(salt_str) → new_str
Applies a one-way cryptographic hash to str by invoking the standard library function crypt(3) with the given salt string. While the format and the result are system and implementation dependent, using a salt matching the regular expression \A[a-zA-Z0-9./]{2} should be valid and safe on any platform, in which only the first two characters are significant.

This method is for use in system specific scripts, so if you want a cross-platform hash function consider using Digest or OpenSSL instead.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
34
Q

delete

A

delete([other_str]+) → new_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”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
35
Q

delete!

A

delete!([other_str]+) → str or nil

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
36
Q

downcase

A

downcase → new_str
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”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
37
Q

downcase!

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
38
Q

dump

A

dump → new_str
Produces a version of str with all non-printing characters replaced by \nnn notation and all special characters escaped.

“hello \n ‘’“.dump #=> “"hello \n ‘’"

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
39
Q

each_byte

A

each_byte {|fixnum| block } → 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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
40
Q

each_char

A

each_char {|cstr| block } → 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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
41
Q

each_codepoint

A

each_codepoint {|integer| block } → 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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
42
Q

each_line

A

each_line(separator=$/) {|substr| block } → str
each_line(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"
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
43
Q

empty?

A

empty? → true or false
Returns true if str has a length of zero.

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
44
Q

encode

A

encode(encoding [, options] ) → str
encode(dst_encoding, src_encoding [, options] ) → str
encode([options]) → str

The first form returns a copy of str transcoded to encoding encoding. The second form returns a copy of str transcoded from src_encoding to dst_encoding. The last form returns a copy of str transcoded to Encoding.default_internal.

By default, the first and second form raise Encoding::UndefinedConversionError for characters that are undefined in the destination encoding, and Encoding::InvalidByteSequenceError for invalid byte sequences in the source encoding. The last form by default does not raise exceptions but uses replacement strings.

The options Hash gives details for conversion and can have the following keys:

:invalid
If the value is :replace, encode replaces invalid byte sequences in str with the replacement character. The default is to raise the Encoding::InvalidByteSequenceError exception

:undef
If the value is :replace, encode replaces characters which are undefined in the destination encoding with the replacement character. The default is to raise the Encoding::UndefinedConversionError.

:replace
Sets the replacement string to the given value. The default replacement string is “uFFFD” for Unicode encoding forms, and “?” otherwise.

:fallback
Sets the replacement string by the given object for undefined character. The object should be a Hash, a Proc, a Method, or an object which has [] method. Its key is an undefined character encoded in the source encoding of current transcoder. Its value can be any encoding until it can be converted into the destination encoding of the transcoder.

:xml
The value must be :text or :attr. If the value is :text encode replaces undefined characters with their (upper-case hexadecimal) numeric character references. ‘&’, ‘’ are converted to “&”, “<”, and “>”, respectively. If the value is :attr, encode also quotes the replacement result (using ‘“’), and replaces ‘”’ with “"”.

\:cr_newline
Replaces LF (“n”) with CR (“r”) if value is true.
\:crlf_newline
Replaces LF (“n”) with CRLF (“rn”) if value is true.
\:universal_newline
Replaces CRLF (“rn”) and CR (“r”) with LF (“n”) if value is true.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
45
Q

encode!

A

encode!(encoding [, options] ) → str
encode!(dst_encoding, src_encoding [, options] ) → str
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 #encode for details. Returns the string even if no changes were made.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
46
Q

encoding

A

encoding → encoding

Returns the Encoding object that represents the encoding of obj.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
47
Q

end_with?

A

end_with?([suffixes]+) → true or false

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

48
Q

eql?

A

eql?(other) → true or false

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

49
Q

force_encoding

A

force_encoding(encoding) → str

Changes the encoding to encoding and returns self.

50
Q

getbyte

A

getbyte(index) → 0 .. 255

returns the indexth byte as an integer.

51
Q

gsub

A
gsub(pattern, replacement) → new_str 
gsub(pattern, hash) → new_str
gsub(pattern) {|match| block } → new_str
gsub(pattern) → enumerator
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]/, ‘’) #=> “hll
“hello”.gsub(/([aeiou])/, ‘’) #=> “hll”
“hello”.gsub(/./) {|s| s.ord.to_s + ‘ ‘} #=> “104 101 108 108 111 “
“hello”.gsub(/(?[aeiou])/, ‘{\k}’) #=> “h{e}ll{o}”
‘hello’.gsub(/[eo]/, ‘e’ => 3, ‘o’ => ‘
’) #=> “h3ll*”

Supplemental notes:

The examples are use regular expressions for the pattern; here are some simple examples using strings:

“Super guper bag”.gsub “g”, “d” # => “Super duper bad”

“Ruby is 13%”.gsub( ‘%’ ) {|c| c.ord.to_s + ‘ ‘ } # => “Ruby is 1337”

“Terribly complex”.gsub “complex”, “simple” # => “Terribly simple”

52
Q

gsub!

A

gsub!(pattern, replacement) → str or nil
gsub!(pattern) {|match| block } → str or nil
gsub!(pattern) → an_enumerator
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.

53
Q

hash

A

hash → fixnum

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

54
Q

hex

A

hex → integer
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

55
Q

include?

A

include? other_str → true or false
Returns true if str contains the given string or character.

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

56
Q

index

A

index(substring [, offset]) → fixnum or nil
index(regexp [, offset]) → fixnum or nil
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
57
Q

replace

A

replace(other_str) → str
Replaces the contents and taintedness of str with the corresponding values in other_str.

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

58
Q

insert

A

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"
59
Q

inspect

A

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

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

60
Q

intern

A

intern → symbol
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”

61
Q

length

A

length → integer

Returns the character length of str.

62
Q

lines

A

lines(separator=$/) → an_array
Returns an array of lines in str split using the supplied record separator ($/ by default). This is a shorthand for str.each_line(separator).to_a.

If a block is given, which is a deprecated form, works the same as each_line.

63
Q

ljust

A

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”

64
Q

lstrip

A

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”

65
Q

lstrip!

A

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

66
Q

match

A

match(pattern) → matchdata or nil
match(pattern, pos) → matchdata or nil
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')      #=> #
'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.

67
Q

next

A

next → new_str
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"
"<>".succ   #=> "<>"
"1999zzz".succ     #=> "2000aaa"
"ZZZ9999".succ     #=> "AAAA0000"
"***".succ         #=> "**+"
68
Q

next!

A

next! → str

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

69
Q

oct

A

oct → integer
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

70
Q

ord

A

ord → integer
Return the Integer ordinal of a one-character string.

“a”.ord #=> 97

71
Q

partition

A

partition(sep) → [head, sep, tail]
partition(regexp) → [head, match, tail]
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”]

72
Q

prepend

A

prepend(other_str) → str
Prepend—Prepend the given string to str.

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

73
Q

replace

A

replace(other_str) → str
Replaces the contents and taintedness of str with the corresponding values in other_str.

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

74
Q

reverse

A

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

“stressed”.reverse #=> “desserts”

75
Q

reverse!

A

reverse! → str

Reverses str in place.

76
Q

rindex

A

rindex(substring [, fixnum]) → fixnum or nil
rindex(regexp [, fixnum]) → fixnum or nil
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
77
Q

rjust

A

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”

78
Q

rpartition

A

rpartition(sep) → [head, sep, tail]
rpartition(regexp) → [head, match, tail]
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”]

79
Q

rstrip

A

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”

80
Q

rstrip!

A

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

81
Q

scan

A

scan(pattern) → array
scan(pattern) {|match, …| block } → str
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 "<> " }
print "\n"
a.scan(/(.)(.)/) {|x,y| print y, x }
print "\n"
produces:

<> <>
rceu lowlr

82
Q

scrub

A

scrub → new_str
scrub(repl) → new_str
scrub{|bytes|} → new_str
If the string is invalid byte sequence then replace invalid bytes with given replacement character, else returns self. If block is given, replace invalid bytes with returned value of the block.

“abc\u3042\x81”.scrub #=> “abc\u3042\uFFFD”
“abc\u3042\x81”.scrub(“”) #=> “abc\u3042
“abc\u3042\xE3\x80”.scrub{|bytes| ‘’ } #=> “abc\u3042”

83
Q

scrub!

A

scrub! → str
scrub!(repl) → str
scrub!{|bytes|} → str
If the string is invalid byte sequence then replace invalid bytes with given replacement character, else returns self. If block is given, replace invalid bytes with returned value of the block.

“abc\u3042\x81”.scrub! #=> “abc\u3042\uFFFD”
“abc\u3042\x81”.scrub!(“”) #=> “abc\u3042
“abc\u3042\xE3\x80”.scrub!{|bytes| ‘’ } #=> “abc\u3042”

84
Q

setbyte

A

setbyte(index, integer) → integer

modifies the indexth byte as integer.

85
Q

size

A

size → integer

Returns the character length of str.

86
Q

slice

A
slice(index) → new_str or nil
slice(start, length) → new_str or nil
slice(range) → new_str or nil
slice(regexp) → new_str or nil
slice(regexp, capture) → new_str or nil
slice(match_str) → new_str or nil
Element Reference — If passed a single index, returns a substring of one character at that index. If passed a start index and a length, returns a substring containing length characters starting at the index. If passed a range, its beginning and end are interpreted as offsets delimiting the substring to be returned.

In these three cases, if an index is negative, it is counted from the end of the string. For the start and range cases the starting index is just before a character and an index matching the string’s size. Additionally, an empty string is returned when the starting index for a character range is at the end of the string.

Returns nil if the initial index falls outside the string or the length is negative.

If a Regexp is supplied, the matching portion of the string is returned. If a capture follows the regular expression, which may be a capture group index or name, follows the regular expression that component of the MatchData is returned instead.

If a match_str is given, that string is returned if it occurs in the string.

Returns nil if the regular expression does not match or the match string cannot be found.

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[11, 0] #=> “”
a[11] #=> nil
a[12, 0] #=> nil
a[12..-1] #=> nil

a[/aeiou\1/] #=> “ell”
a[/aeiou\1/, 0] #=> “ell”
a[/aeiou\1/, 1] #=> “l”
a[/aeiou\1/, 2] #=> nil

a[/(?[aeiou])(?[^aeiou])/, “non_vowel”] #=> “l”
a[/(?[aeiou])(?[^aeiou])/, “vowel”] #=> “e”

a[“lo”] #=> “lo”
a[“bye”] #=> nil

87
Q

slice!

A
slice!(fixnum) → fixnum or nil
slice!(fixnum, fixnum) → new_str or nil
slice!(range) → new_str or nil
slice!(regexp) → new_str or nil
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!(/s.*t/)   #=> "sa st"
string.slice!("r")      #=> "r"
string                  #=> "thing"
88
Q

split

A

split(pattern=$;, [limit]) → anArray
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.

When the input str is empty an empty Array is returned as the string is considered to have no fields to split.

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

”“.split(‘,’, -1) #=> []

89
Q

squeeze

A

squeeze([other_str]*) → new_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”

90
Q

squeeze!

A

squeeze!([other_str]*) → str or nil

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

91
Q

start_with?

A

start_with?([prefixes]+) → true or false
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
92
Q

strip

A

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

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

93
Q

strip!

A

strip! → str or nil

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

94
Q

sub

A

sub(pattern, replacement) → new_str
sub(pattern, hash) → new_str
sub(pattern) {|match| block } → new_str
Returns a copy of str with the first occurrence of pattern replaced by 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]/, ‘’) #=> “hllo”
“hello”.sub(/([aeiou])/, ‘’) #=> “hllo”
“hello”.sub(/./) {|s| s.ord.to_s + ‘ ‘ } #=> “104 ello”
“hello”.sub(/(?[aeiou])/, ‘\k’) #=> “hello”
‘Is SHELL your preferred shell?’.sub(/[[:upper:]]{2,}/, ENV)
#=> “Is /bin/bash your preferred shell?”
Supplemental notes

The examples all use regular expressions for the pattern; here are some simple examples using strings:

“Super bag”.sub “g”, “d” # => “Super bad”

“Ruby is 13%”.sub( ‘%’ ) {|c| c.ord.to_s + ‘ ‘ } #=> “Ruby is 1337”

“Terribly complex”.gsub “complex”, “simple” # => “Terribly simple”

95
Q

sub!

A

sub!(pattern, replacement) → str or nil
sub!(pattern) {|match| block } → str or nil
Performs the same substitution as #sub in-place.

Returns str if a substitution was performed or nil if no substitution was performed.

96
Q

succ

A

succ → new_str
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"
"<>".succ   #=> "<>"
"1999zzz".succ     #=> "2000aaa"
"ZZZ9999".succ     #=> "AAAA0000"
"***".succ         #=> "**+"
97
Q

succ!

A

succ! → str

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

98
Q

sum

A

sum(n=16) → integer
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.

99
Q

swapcase

A

swapcase → new_str
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”

100
Q

swapcase!

A

swapcase! → str or nil
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.

101
Q

to_c

A

to_c → complex
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.

'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)
See Kernel.Complex.
102
Q

to_f

A

to_f → float
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

103
Q

to_i

A

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 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
104
Q

to_r

A

to_r → rational
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.

'  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)
See Kernel.Rational.
105
Q

to_s

A

to_s → str
to_str → str
Returns the receiver.

106
Q

to_str

A

to_str → str

Returns the receiver.

107
Q

to_sym

A

to_sym → symbol
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”

108
Q

tr

A

tr(from_str, to_str) => new_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’, ‘’) #=> “hll
“hello”.tr(‘aeiou’, ‘AA
’) #=> “hAll*”
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”
The backslash character </code> can be used to escape <code>^ or - and is otherwise ignored unless it appears at the end of a range or the end of the from_str or to_str:</code>

“hello^world”.tr(“\^aeiou”, “”) #=> “hllwrld”
“hello-world”.tr(“a\-eo”, “
”) #=> “hll**wrld”

“hello\r\nworld”.tr(“\r”, “”) #=> “hello\nworld”
“hello\r\nworld”.tr(“\r”, “”) #=> “hello\r\nwold”
“hello\r\nworld”.tr(“\\r”, “”) #=> “hello\nworld”

“X[’\b’]”.tr(“X\”, “”) #=> “[‘b’]”
“X[’\b’]”.tr(“X-\]”, “”) #=> “‘b’”

109
Q

tr!

A

tr!(from_str, to_str) → str or nil

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

110
Q

tr_s

A

tr_s(from_str, to_str) → new_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’, ‘’) #=> “ho”
“hello”.tr_s(‘el’, ‘hx’) #=> “hhxo”

111
Q

tr_s!

A

tr_s!(from_str, to_str) → str or nil

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

112
Q

unpack

A
unpack(format) → anArray
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(‘ZZ’) #=> [“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”]

See table on http://www.ruby-doc.org/core-2.1.3/String.html for summary on the various formats and the Ruby classes returned by each.

113
Q

upcase

A

upcase → new_str
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”

114
Q

upcase!

A

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

115
Q

upto

A

upto(other_str, exclusive=false) {|s| block } → str
upto(other_str, exclusive=false) → an_enumerator
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”]

116
Q

valid_encoding?

A

valid_encoding? → true or false
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