Keyword Array Hash String 2D Case Class Console Convert DateTime Duplicates Exception File Format If Iterator Math Method Nil Number Recursion Regexp Replace Set Sort Split Substring While


Strings. 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.

Often, strings are part of more complex data structures. We access them with iterators and loops (preferring iterators for clearer code). The operator "<<" appends strings.

Literals. 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 two 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.

Based on:

Ruby 2

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.
puts value1
puts value2
puts value3


This is "ruby" string
This is also 'one'
This is another "string"

Upcase, downcase. 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.
puts upper
puts lower


dot net perls

Concatenate. 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.
puts value3



Length. 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.
puts test2
puts test2.length



Each_char. 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.

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.
    puts c



Each_line. 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.
    puts line



Include. 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 that uses include method

value = "plato"

# String includes "to".
if value.include? "to"
    puts "1"

# String does not include "not".
if !value.include? "not"
    puts "2"

# String does not include "PLA" uppercase.
if !value.include? "PLA"
    puts "3"



Insert. 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 that uses insert

# 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



Center. 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 that uses center

# This string has 8 chars.
value = "prytanes"

# Center with spaces to size of 10.
a =
puts "[" + a + "]"

# Center with stars to size of 13.
b =, "*")
puts b


[ prytanes ]

Chomp. 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 that uses chomp

# 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"
puts value3

# An argument specifies a part to be removed.
value4 = "european"
value4.chomp! "an"
puts value4



Append. 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 that uses append

value = "cat"
puts value

# Append this string (surrounded by spaces).
value << " in "
puts value

# Append another string.
value << "the hat"
puts value


cat in
cat in the hat

Count. 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 that uses count method

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



Crypt. 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 that uses crypt

# 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



Reverse. 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 that uses reverse

value = "rat"

# Reverse in-place.
# ... Without an exclamation, reverse returns a new string.
puts value



Replace. 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

Split. 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.


Ciphers. 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.


Substring. There is no substring method on strings. But we can use ranges, indexes, and regular expressions to extract (and change) substrings.


String arrays. 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.