A string is a data type used to represent textual data. For 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'
puts greeting
put language
Output
Good Morning 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}
Yes! Ruby lets you insert expressions, not just variables, inside a string using string interpolation. 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. Here are a few ways to perform it:
1. Using the + operator
You can join two strings with the +
operator:
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 []
. For example,
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; that means you can call methods on them to perform operations like changing case, checking length, or replacing characters.
Some common string methods are:
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. |
Next, let's explore a few of these methods with examples.
Example 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,
upcase
converts all letters to uppercase:"hello"
to"HELLO"
.downcase
converts all letters to lowercase:"WORLD"
to"world"
.
Example 2: Get the Length of a String
To find the number of characters in a string, use the .length
method.
puts "Ruby".length
# Output: 4
Here, we got the length of "Ruby"
, which is 4.
Example 3: Remove Extra Spaces
To remove spaces from the beginning and end of a string, use the .strip
method.
puts " hello "
puts " hello ".strip
Output
hello hello
Example 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"
.
Example 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")
puts "ruby programming".include?("python")
Output
true false
Here, the string "ruby programming"
- Contains
"ruby"
, so the method returnstrue
. - Doesn't contain
"python"
, so the method returnsfalse
.
Also, if you want to search "uby"
, it will still return true
because "uby"
exists as a part of "ruby"
in the string.
Example 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"]