Ruby Strings
A string is a piece of text written inside quotes. Double quotes let a string hold values placed inside the text.
Values inside double quotes
The marks #{...} inside double quotes stand for a value. Single quotes print those same marks as plain text.
name = "Ana"
puts "Hello, #{name}!"
puts 'Hello, #{name}!'Joining strings with +
The + sign joins two strings end to end. The joined strings print as one line.
first = "Hello, "
second = "Ana"
puts first + secondText plus a number fails
A string and a number cannot join with +. Ruby stops and prints an error line.
puts "Score: " + 42Interpolation is the fix
Placing the number inside #{...} prints it as part of the text. The program runs with no error.
puts "Score: #{42}"Reading letters by position
Square brackets read letters by position. Two values give a start position and a count of letters.
puts "Hello"[1]
puts "Hello"[1, 2]Example
player = "Ana"
score = 42
puts "#{player} scored #{score} points"
puts player[0]
puts player[1, 2]Key points
- Use #{...} inside double quotes to place a value in the text.
- Single quotes print #{...} as plain text.
- Use + to join two strings into one string.
- A string plus a number stops the program with an error.
- The first letter of a string sits at position 0.
- A slice reads a run of letters with a start position and a count.
In this example, player holds the string Ana and score holds the number 42. The first print places both values inside one string. The second print reads the letter at position 0. The third print reads two letters from position 1.
Note
A value inside #{...} needs no joining and no type change.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz Ruby Compiler
Exercise
What prints when a string in single quotes holds the text Total: #{5 + 3}?