Global Substitution - Learn Ruby The Beginner Guide An Introduction to Ruby Programming (2015)

Learn Ruby The Beginner Guide An Introduction to Ruby Programming (2015)

Global Substitution

We should work some more with if/else statements. In this exercise we're going to use them to swap some words around. Let's imagine we're correcting answers from a jeopardy transcript. In Jeopardy an answer is given and then the contestants give the question to what that would be the answer to. Maybe we'll use Family Feud in another chapter.

answer = "What is Jurassic Park?"

if answer.include? "What"

answer.gsub!(/What/, "Where")

else

puts "No error here."

end

puts answer

Where is Jurassic Park?

We use .include? to ask if our variable includes What. If it does then we use .gsub! to swap What with Where.

Arrays

An array is a list of elements. Recall that we can create a variable that's equal to a single thing. A spaghetti noodle for instance. An array can be thought of as the whole meal.

my_array = ["sauce", "noodles", "parmesan", "meatballs"]

puts my_array

sauce

noodles

parmesan

meatballs

Remember when we targeted specific letters in a string? We can do the same with this array. When we call the index number it will pull up the whole item. Like so:

puts my_array[2]

parmesan

High five! Now, tell yourself who's becoming a Ruby champ by throwing this down:

puts my_array[2][3..4]

me

The first index call [2] is selecting the string parmesan. The second index call [3..4] is selecting the letters within that string.