A string is a data type used to represent textual data.
Here's a simple example of strings in Ruby. You can read the rest of the tutorial to learn more.
Example
message = "Hello, world!"
puts message
# Output: Hello, world!
Here, "Hello, world!" is a string that is stored inside the message variable.
Create a String
In Ruby, you can create a string by wrapping text in double quotes (") or single quotes ('). For example,
greeting = "Good Morning"
language = 'Ruby'
Here, "Good Morning" and 'Ruby' are strings.
Note: Ruby strings are case-sensitive — uppercase and lowercase letters are treated as different.
For example, "Good Morning" is different from "good morning" because "G" and "g" are treated as different values.
String Interpolation
String interpolation lets you insert the value of a variable inside a string. For example,
name = "Taylor"
puts "Hello #{name}"
Output
Hello Taylor
Inside the string, #{name} tells Ruby to look at the name variable and insert its value right there.
However, string interpolation works only inside double-quoted strings. It won't work inside single-quoted strings. For example,
name = "Taylor"
puts 'Hello #{name}'
Output
Hello #{name}
Frequently Asked Questions
Yes! Ruby lets you insert expressions, not just variables, inside a string using #{...}. For example,
puts "2 + 2 is #{2 + 2}"
Output
2 + 2 is 4
Here,
- Ruby first evaluates the expression inside
#{}, which is2 + 2. - The result, 4, replaces the entire
#{2 + 2}part. - So the final string becomes:
"2 + 2 is 4".
String Concatenation
String concatenation means joining strings together to form a single string.
In Ruby, there are a few ways to perform string concatenation.
1. Using the + operator
You can join two strings with the + sign:
first_name = "Amber"
last_name = "Smith"
# Concatenates the first and last name with a space in between
puts first_name + " " + last_name
Output
Amber Smith
In the above example, we joined "Amber", a space " ", and "Smith" into one full string using the + operator.
2. Using the << operator
You can use the << operator to add one string to the end of another. For example,
greeting = "Hello"
greeting << ", world!"
puts greeting
Output
Hello, world!
Accessing Characters in a String
Ruby strings are made up of characters, and each character has a position (called an index), starting from 0.
You can access individual characters in a string using square brackets [].
text = "hello"
puts text[0]
puts text[1]
Output
h e
In this example:
text[0]gives you the first character:"h".text[1]gives you the second character:"e".
Ruby String Methods
In Ruby, strings are objects — and that means you can call methods on them to perform operations like changing case, checking length, or replacing characters.
Let's see some of the common string operations using methods.
1. Change the Case of a String
To change the case of a string, you can use the .upcase and .downcase methods.
puts "hello".upcase
puts "WORLD".downcase
# Output:
# HELLO
# world
Here,
upcaseconverts all letters to uppercase:"hello"to"HELLO".downcaseconverts all letters to lowercase:"WORLD"to"world".
2. Get the Length of a String
To find out how many characters are in a string, use the .length method.
puts "Ruby".length
# Output: 4
3. Remove Extra Spaces
To remove spaces from the beginning and end of a string, use the .strip method.
puts " hello ".strip
# Output: hello
4. Replace Part of a String
To replace parts of a string with something else, use the .gsub method.
puts "dog".gsub("d", "f")
puts "I like cats and cats like me".gsub("cats", "dogs")
# Output:
# fog
# I like dogs and dogs like me
The gsub method replaces all occurrences of the matched string or pattern in the given string. For example, both instances of "cats" are replaced with "dogs".
5. Check if a String Contains Something
To check whether a certain word or letter exists in a string, use the .include? method.
The .include? the method returns true if the given substring is found inside the string, else it returns false.
puts "ruby programming".include?("ruby")
# Output: true
Here, the string "ruby programming" contains "ruby", so the method returns true.
Also, if you want to search "uby", it will still return true because "uby" exists as a part of "ruby" in the string.
6. Split a String into Parts
To break a string into an array of smaller strings, use the .split method.
p "one two three".split
# Output: ["one", "two", "three"]
By default, split divides the string into an array of words using whitespace as the separator.
You can also split by another character, like a comma:
p "apple,banana,grape".split(",")
# Output: ["apple", "banana", "grape"]
You've already seen common string methods like upcase, length, include?, and gsub.
Here is a quick reference of methods that includes some of those, plus a few more you might find helpful:
| Method | Description |
|---|---|
upcase |
Converts all letters to uppercase. |
downcase |
Converts all letters to lowercase. |
strip |
Removes whitespace from both ends of the string. |
length |
Returns the number of characters in the string. |
include?("x") |
Returns true if the string contains "x"; otherwise false. |
gsub("a", "b") |
Replaces all occurrences of "a" with "b". |
sub("a", "b") |
Replaces the first occurrence of "a" with "b". |
split(" ") |
Splits the string into an array, using a space (or other delimiter). |
chars |
Returns an array of individual characters. |
slice(start, len) |
Returns a substring from the given start index and length. |
capitalize |
Capitalizes only the first letter of the string. |
reverse |
Reverses the string content. |