Strings and interpolation
You can embed variables right inside a string – that's called interpolation and works with #{} inside double quotes:
animal = "fox"
"The #{animal} shouts!"Ruby evaluates whatever is between #{ and } and inserts the result. Math works too:
"#{3 * 7} strips of bacon"Important: interpolation only happens inside double quotes. Inside single quotes the text stays exactly as written – #{} included:
puts "The #{animal} shouts!"
puts 'The #{animal} shouts!'Strings can be put together, too: + joins two strings, * repeats one. And \n inside double quotes is a line break:
puts "Chunky" + " " + "Bacon"
puts "Bacon! " * 3
puts "First line\nSecond line"Strings are objects with dozens of methods. A few favorites – each returns a new result, while the string itself stays as it is:
greeting = "chunky bacon"
puts greeting.upcase # CAPITAL LETTERS
puts greeting.capitalize # first letter capitalized
puts greeting.length # number of characters
puts greeting.reverse # backwards
puts greeting.include?("bacon") # does "bacon" occur in it?
greeting.sub("bacon", "fox") # replaceMethods can be chained: greeting.upcase.reverse first capitalizes, then reverses the result. Methods ending in ? answer a yes-or-no question with true or false.
Square brackets pick single characters out. Counting starts at 0, and negative numbers count from the end: [-1] is the last character. [0, 6] means “from position 0, six characters”:
puts greeting[0]
puts greeting[-1]
greeting[0, 6]More good friends: strip removes spaces at the start and end, start_with? and end_with? check the beginning and the end, gsub replaces every occurrence instead of only the first, and center(20, "*") centers a text in a line of stars. Try them in the cell above! What else there is, the docs tell you – lesson 48 shows how to read them.
favorite_food is prepared below. Use interpolation to build the sentence I love CHUNKY BACON! – the variable goes into the string with #{}, and one of the methods above makes it loud.favorite_food = "Chunky Bacon"
# "I love ...!"
word: backwards – the word reversed; palindrome – true when the word in lower case equals its reverse; and length – the number of its characters.word = "Racecar"
# backwards = ... # the word reversed
# palindrome = ... # true when the word reads the same backwards (ignore the case)
# length = ... # how many characters