Ruby String Examples (each char, each line)Use strings: create literals, manipulate strings and use each char and each line.
String. A string contains text data. Strings are extensively used. In Ruby, we have powerful methods to transform, combine and test string data.
Strings are part of more complex data structures. We access them with iterators and loops (preferring iterators for clearer code). The operator "<<" appends strings.
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.
Here: In this example, we use the percent "%" character at the start of 2 literals.
And: In this form, we can use another character, such as a vertical bar or "+" as a delimiter. We can avoid escaping double-quotes.
Ruby program that uses string literals
# String literals.
value1 = %|This is "ruby" string|
value2 = %+This is also 'one'+
value3 = "This is another \"string\""
# Display results.
This is "ruby" string
This is also 'one'
This is another "string"
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.
Ruby program that uses upcase, downcase
# An input string.
value = "Dot Net Perls"
# Change cases.
upper = value.upcase()
lower = value.downcase()
# Display results.
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.
Here: We add two string variables, value1 and value2, along with the "/" literal. We display the result.
Ruby program that concatenates strings
# Two string values.
value1 = "Ruby"
value2 = "Python"
# Concatenate the string values.
value3 = value1 + "/" + value2;
# Display the result.
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.
Multiplication: This program also multiplies a string. This concatenates the same string several times. It changes "1" to "111" here.
Ruby program that computes string length
# An input string.
test = "1"
# Multiply the string by 3.
test2 = test * 3
# Display string and its length.
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.Iterator
Next: On the next iteration, it is assigned to the next char. In the example, "c" is the current char.
Tip: As with other "each" iterators, this reduces the possibility of errors when looping in programs.
Ruby program that uses each_char
value = "ruby"
# Loop over each character with each_char.
value.each_char do |c|
# Write char.
This iterator loops over all the lines in a string. If your input string has newlines, each_line will return separated strings.
Important: If no newlines occur in the string, only one string will be returned by each_line.
Ruby program that uses each_line
# String literal with two newline characters.
data = "Ruby\nPython\nPerl"
# Loop over lines with each_line.
data.each_line do |line|
# Write line.
Is one string contained within another? The "include?" method in Ruby tells us. It searches one string for a second string. It returns true or false.
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".
Ruby program that uses include method
value = "plato"
# String includes "to".
if value.include? "to"
# String does not include "not".
if !value.include? "not"
# String does not include "PLA" uppercase.
if !value.include? "PLA"
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.
Invalid: With an invalid index, the insert() method will throw an IndexError. We may need to check against the string's length.
Negative: With a negative index, the insertion is based on the last index. If we pass -1, the insertion occurs before the last character.
Ruby program that uses insert
# Input string.
value = "socrates"
# Insert string into the input string.
# Now prepend two characters.
Sometimes a string must be centered in program output. This is helpful for preformatted text like HTML. The center method evenly pads 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.
Ruby program that uses center
# This string has 8 chars.
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, "*")
[ prytanes ]
This 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. A 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.
Ruby program that uses chomp
# Chomp removes ending whitespaces and returns a copy.
value = "egypt\r\n"
value2 = value.chomp
# Chomp! modifies the string in-place.
value3 = "england\r\n"
# An argument specifies a part to be removed.
value4 = "european"
Ruby has a special syntax for string appends. It uses the "<<" operator. We can use this operator to combine two or more strings. 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.
Ruby program that uses append
value = "cat"
# Append this string (surrounded by spaces).
value << " in "
# Append another string.
value << "the hat"
cat in the hat
This method counts characters, not substrings. It receives a string containing a set of characters. It returns the total number of those characters it finds.
Range: We can use a range of characters within the argument to count: "a-c" means "abc."
Ruby program that uses count method
value = "Plutarch"
# The letter "a" occurs once.
a = value.count "a"
# The letters "a" and "r" occur twice in total.
b = value.count "ar"
# Letters in range "a" through "c" occur twice in total.
c = value.count "a-c"
This method encrypts a string. It cannot be decrypted: it is one-way. We must provide two bytes of a "salt" string to invoke crypt. Two characters are required.
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.
Deterministic: With the same salt argument, crypt() is deterministic. So one use for it is storing the result of crypt for a string.
Ruby program that uses crypt
# Crypt this string with salt string "aa".
value = "ruby"
result = value.crypt "aa"
# Crypt another value.
value = "sapphire"
result = value.crypt "99"
This method inverts the order of characters in a string. This method is rarely useful, but helps when a string has characters that are a form of data (not text).
Sort: A string's letters cannot be directly sorted. But we can convert the string to an array, and sort that.Sort, String
Ruby program that uses reverse
value = "rat"
# Reverse in-place.
# ... Without an exclamation, reverse returns a new string.
If you wish to use a for-loop over a string, this is possible in Ruby. But the each_char method is often a better choice.Length
The sub() and gsub() methods can replace strings. To replace all matches in a string, we must use the gsub method. Sub() replaces only the first match.Sub, gsub: Replace
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.Split
These change letters in text. The ROT13 cipher, for example, shifts characters 13 places. It is easily reversed. We implement ROT13 in Ruby with the tr (translate) method.ROT13
There is no substring method on strings. But we can use ranges, indexes, and regular expressions to extract (and change) substrings.Substring
Often we need to store many strings together. We can concatenate them into a single string. But a string array is often a clearer, faster choice.String Arrays
A summary. String support in Ruby is complete and well-designed. Strings are common. They are often stored in collections like Arrays and Hashes.
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to email@example.com.