String Flashcards
What are String objects?
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#[ ]=.
new
new(str=””) → new_str
Returns a new string object containing a copy of str.
try_convert
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
%
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"
*
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 #=> “”
+
str + other_str → new_str
Concatenation—Returns a new String containing other_str concatenated to str.
“Hello from “ + self.to_s #=> “Hello from main”
«
str «_space;integer → str
str «_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 «_space;“world” #=> “hello world”
a.concat(33) #=> “hello world!”
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
==
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
===
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.
=~
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.
[]
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
[]=
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.
ascii_only?
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
b
b → str
Returns a copied string whose encoding is ASCII-8BIT.
bytes
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.
bytesize
bytesize → integer
Returns the length of str in bytes.
“\x80\u3042”.bytesize #=> 4
“hello”.bytesize #=> 5
byteslice
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”
capitalize
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”
capitalize!
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
casecmp
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
center
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”
chars
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.
chomp
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"
chomp!
chomp!(separator=$/) → str or nil
Modifies str in place as described for String#chomp, returning str, or nil if no modifications were made.
chop
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 #=> ""
chop!
chop! → str or nil
Processes str as for String#chop, returning str, or nil if str is the empty string. See also String#chomp!.
chr
chr → string
Returns a one-character string at the beginning of the string.
a = “abcde”
a.chr #=> “a”
clear
clear → string
Makes string empty.
codepoints
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.
concat
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 «_space;“world” #=> “hello world”
a.concat(33) #=> “hello world!”
count
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
crypt
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.
delete
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”
delete!
delete!([other_str]+) → str or nil
Performs a delete operation in place, returning str, or nil if str was not modified.
downcase
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”
downcase!
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.
dump
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 ‘’"
each_byte
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
each_char
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
each_codepoint
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
each_line
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"
empty?
empty? → true or false
Returns true if str has a length of zero.
“hello”.empty? #=> false
“ “.empty? #=> false
““.empty? #=> true
encode
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.
encode!
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.
encoding
encoding → encoding
Returns the Encoding object that represents the encoding of obj.