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"
^ or - and is otherwise ignored unless it appears at the end of a sequence or the end of a other_str.
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
^ or - and is otherwise ignored unless it appears at the end of a range or the end of the from_str or to_str:
"hello^world".tr("\\^aeiou", "*") #=> "h*ll**w*rld"
"hello-world".tr("a\\-eo", "*") #=> "h*ll**w*rld"
"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'"