text_fieldsStrings
In Ruby, strings are objects that represent sequences of characters. They are created by enclosing the characters within either single quotes (') or double quotes ("). You will find the difference between them later in this lesson.
"Hello World" #=> "Hello World"
'Hello World' #=> 'Hello World'
Concatenation refers to the process of combining strings together to create a single string. There are several ways to concatenate strings in Ruby.
# Using + operator
"Hello" + " " + "World!" #=> "Hello World!
# Using << operators
greeting = "Hello"
greeting << " "
greeting << "World!"
greeting #=> "Hello World!"
# Using concat method
"Hello".concat(" ").concat(" World!") #=> "Hello World!"
String interpolation is a feature that allows you to embed expressions or variables directly within a string literal. When using double-quoted strings (""), Ruby evaluates the expressions and substitutes them with their values before assigning the result to the string variable. This provides a convenient way to construct strings dynamically.
name = "John"
age = 25
text = "My name is #{name}, and I'm #{age} years old!"
text # => "My name is John, and I'm 25 years old!"
String interpolation works only with double-quoted strings (""). Single-quoted strings ('') do not perform interpolation; they treat variables as normal text.
name = "John"
age = 25
text = 'My name is #{name}, and I'm #{age} years old!'
text # => "My name is #{name}, and I'm #{age} years old!"
In Ruby, you can extract a substring from a string using the [] method or the slice method. Both methods allow you to specify the starting index and optionally the length of the substring to extract.
string = "Hello, world!"
# Extract a substring starting at index 0 and ending at index 3
string[0..3] #=> "Hell"
string[..3] #=> "Hell"
# Extract a substring from index 7 to end
string[7..-1] #=> "world!"
string[7..] #=> "world!"
# Extract a substring from index 7 to index before the last one
string[7..-2] # => #=> "world"
# Extract a substring from index 7 and take next 5 character
string[7, 5] # => #=> "world"
Method slice works in the same way so you can use it interchangeably.
string = "Hello, world!"
string.sustring(0..3) #=> "Hell"
string.substring(7..-1) #=> "world!"
string.substring(7, 5) # => #=> "world"
Ruby provides a rich set of built-in methods for working with strings. Here are some of them.
# Returns the length of the string
"Hello".length #=> 5
"Hello".size #=> 5
# Convert string to upcase/downcase
"Hello".upcase #=> "HELLO"
"Hello".downcase #=> "hello"
# Capitalize word
"hELLO".capitalize #=> "Hello"
# Return index of the first occurrence of a substring
"Hello".index("l") #=> 2
# Checks if a substring is present in the string.
"Hello".include?("llo") #=> true
# Checks if the string starts or ends with a specific substring
"hello".start_with?("he") #=> true
"hello".end_with?("lo") #=> true