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'
Concatenation refers to the process of combining strings together to create a single string. There are several ways to concatenate strings in Ruby.
"Hello" + " " + "World!"
greeting = "Hello"
greeting << " "
greeting << "World!"
greeting
"Hello".concat(" ").concat(" 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
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
text
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!"
string[0..3]
string[..3]
string[7..-1]
string[7..]
string[7..-2]
string[7, 5]
Method slice works in the same way so you can use it interchangeably.
string = "Hello, world!"
string.sustring(0..3)
string.substring(7..-1)
string.substring(7, 5)
Ruby provides a rich set of built-in methods for working with strings. Here are some of them.
"Hello".length
"Hello".size
"Hello".upcase
"Hello".downcase
"hELLO".capitalize
"Hello".index("l")
"Hello".include?("llo")
"hello".start_with?("he")
"hello".end_with?("lo")