Array Hash String Case Class Convert DateTime Exception File Format If Iterator Loop Math Method Nil Number Regexp Set Sort Split
A string holds characters. It contains text data. In programming, strings are extensively used. In Ruby, we have powerful methods to transform, combine and test string data. Strings are part of many data structures.
Based on: Ruby 2.0.0
A string literal is string data directly specified in a program. In Ruby, we use the single-quote, or double-quote character to create string literals. And more advanced syntax forms are available.
Here:In this example, we use the percent "%" character at the start of two literals.
And:In this form, we can use another character, such as "|" or "+" as a delimiter. We can avoid escaping double-quotes.
Program that uses string literals: Ruby # String literals. value1 = %|This is "ruby" string| value2 = %+This is also 'one'+ value3 = "This is another \"string\"" # Display results. puts value1 puts value2 puts value3 Output This is "ruby" string This is also 'one' This is another "string"
Letters are either lowercase or uppercase. In Ruby, the upcase() and downcase() methods affect letters. Upcase changes lowercase letters to uppercase. And downcase changes uppercase letters to lowercase.
Tip:You must assign to the result of upcase() and downcase(). The original string instance is not modified.
Instead:A modified copy of the string is made.
This is returned.
We assign to this reference.
Program that uses upcase, downcase: Ruby # An input string. value = "Dot Net Perls" # Change cases. upper = value.upcase() lower = value.downcase() # Display results. puts upper puts lower Output DOT NET PERLS dot net perls
Two or more strings can be combined into one. This is called concatenation. In Ruby we use the plus operator—we add strings together. This yields a new string, containing all the parts in one object.
Here:We add two string variables, value1 and value2, along with the "/" literal. We display the result.
Program that concatenates strings: Ruby # Two string values. value1 = "Ruby" value2 = "Python" # Concatenate the string values. value3 = value1 + "/" + value2; # Display the result. puts value3 Output Ruby/Python
Every string has a length. In Ruby the length() method returns a stored value indicating the length. This method does not count the characters in a loop. A string's length is always known in memory.
Multiplication:This program also multiplies a string.
This concatenates the same string several times.
It changes "1" to "111" here.
Program that computes string length: Ruby # An input string. test = "1" # Multiply the string by 3. test2 = test * 3 # Display string and its length. puts test2 puts test2.length Output 111 3
An iterator can loop over each character in a string. With each_char, we introduce an iteration variable. This is a character in the string. On the next iteration, it is assigned to the next char.
Tip:As with other "each" iterators, this reduces the possibility of errors when looping in programs.Iterators
Program that uses each_char: Ruby value = "ruby" # Loop over each character with each_char. value.each_char do |c| # Write char. puts c end Output r u b y
The each_line iterator loops over all the lines in a string. If your input string has newlines, each_line will return separated strings. This is helpful when parsing files or line-separated data.
Important:If no newlines occur in the string, only one string will be returned by each_line.
Program that uses each_line: Ruby # String literal with two newline characters. data = "Ruby\nPython\nPerl" # Loop over lines with each_line. data.each_line do |line| # Write line. puts line end Output Ruby Python Perl
Is one string contained within another? The "include?" method in Ruby tells us. It searches one string for a second string. It returns true (if the string is found) or false (if it is not).
Here:We see that the string "plato" contains the string "to". It does not contain the string "not".
And:The "include?" method is case-sensitive. This means the string "plato" does not include the string "PLA".
Program that uses include method: Ruby value = "plato" # String includes "to". if value.include? "to" puts "1" end # String does not include "not". if !value.include? "not" puts "2" end # String does not include "PLA" uppercase. if !value.include? "PLA" puts "3" end Output 1 2 3
One string can be inserted into another. We use the insert() method and specify the index where to insert. Often we must first search for the correct index. In this example, we just hard-code the insertion indexes.
With an invalid index, the insert() method will throw an IndexError. If you specify a negative index, the insertion occurs based on the last index. So if you pass -1, the insertion occurs before the last character.
Program that uses insert: Ruby # Input string. value = "socrates" # Insert string into the input string. value.insert(3, "k-") puts value # Now prepend two characters. value.insert(0, "??") puts value Output sock-rates ??sock-rates
Sometimes a string must be centered in program output. This is helpful for preformatted text, as in HTML, or in console program or debug output. We use the center() method on strings to evenly pad the left and right sides.
Tip:You can specify a padding character. The default character is a space, but we can use any character.
Warning:If you call center() on a string that is too long to be centered in that size, the method will do nothing.
Program that uses center: Ruby # 8-char input string. value = "prytanes" # Center with spaces to size of 10. a = value.center(10) puts "[" + a + "]" # Center with stars to size of 13. b = value.center(13, "*") puts b Output [ prytanes ] **prytanes***
Chomp removes the newline characters from the end of a string. So it will remove "\n" or "\r\n" if those characters are at the end. If you specify a string argument, that substring is removed if it is present.
In-place:The "chomp!" method modifies a string in-place. So we don't need to assign to the result of "chomp!" with a string variable.
Chop:This method is similar to chomp, but less safe.
It removes the final character from the input.
This can lead to corrupt data.
Program that uses chomp: Ruby # Chomp removes ending whitespaces and returns a copy. value = "egypt\r\n" value2 = value.chomp puts value2 # Chomp! modifies the string in-place. value3 = "england\r\n" value3.chomp! puts value3 # An argument specifies a part to be removed. value4 = "european" value4.chomp! "an" puts value4 Output egypt england europe
Ruby has a special syntax for string appends. It uses the "<<" operator. We can use this operator to combine two strings: it also works on more than two strings in a single line. Here we append twice to a single string.
Tip:The append operator changes the value of the string. So after we append once, the actual string data is changed.
Tip 2:If you want to retain the original data, you can copy a string by assigning another string reference to it.
Program that uses append: Ruby value = "cat" puts value # Append this string (surrounded by spaces). value << " in " puts value # Append another string. value << "the hat" puts value Output cat cat in cat in the hat
The count method counts characters, not substrings. It receives a string containing a set of characters you want to count. It returns the total number of characters it finds in the source string.
Range:We can use a range of characters within the argument to count: "a-c" means "abc."
Program that uses count method: Ruby value = "Plutarch" # The letter "a" occurs once. a = value.count "a" puts a # The letters "a" and "r" occur twice in total. b = value.count "ar" puts b # Letters in range "a" through "c" occur twice in total. c = value.count "a-c" puts c Output 1 2 2
The crypt method encrypts a string. It cannot be decrypted: it is one-way. We must provide two bytes of a "salt" string to invoke crypt. An error results if fewer than two characters are used.
Tip:If more than two characters are passed to crypt, only the first two characters are used.
Tip 2:The first two characters of the salt string appear at the start of the encrypted string.
With the same salt argument, the crypt method is deterministic. So one use for it is storing the result of crypt for a string. And then if another string has the same crypt value, with the same salt, it is likely the same string.
However:Uses for crypt are limited.
It is not helpful in most programs.
It does not provide strong security.
Program that uses crypt: Ruby # Crypt this string with salt string "aa". value = "ruby" result = value.crypt "aa" puts result # Crypt another value. value = "sapphire" result = value.crypt "99" puts result Output aauZSSiXB7FbU 99MByjDtoc6Tc
Strings often need to be split: this separates them based on a delimiter. In Ruby, we specify either a string or a regular expression as that delimiter. This makes split() a powerful and effective method.Split
String support in Ruby is complete and well-designed. Despite this, careful consideration of strings, and whether other types are superior, is worthwhile. A string is often a less efficient data representation.