Learn Ruby The Beginner Guide An Introduction to Ruby Programming (2015)
String Interpolation
Now that we can get data from the user, we want to take that data and insert it into a string. Here is how we insert a variable into a string: #{variable}
We start with the number sign and then put the variable name inside of curly braces.
puts "What is your name?"
your_name = gets.chomp
puts "Nice to meet you #{your_name}! My name is Kate."
⇩
What is your name?
⇩
Jake #Type your answer here.
⇩
Nice to meet you Jake! My name is Kate.
We use gets.chomp rather than gets because gets returns a new line. We want to chomp it away. Here's what we get otherwise:
puts "What is your name?"
your_name = gets
puts "Nice to meet you #{your_name}! My name is Kate."
⇩
What is your name?
⇩
Jake
⇩
Nice to meet you Jake
! My name is Kate.
Remember the baby T-Rex named Chomper from, "The Land Before Time" series? Me too.
While
The if statement is useful in many ways. However, what if we wanted to continue running an if statement so long as a certain condition was true?
mana = 14
while mana > 3
mana = mana - 3
puts mana
end
⇩
11
8
5
2
In this example we are looping through until our mana is no longer greater than three. Notice that we're putting out the mana that's remaining after each loop.
We want to clean this code up a bit. Let's say we're using a spell that costs 3 mana to cast. We want to know two things: How many times can we cast it and how much mana will we have left after? We're also going to replace the mana = mana - 3 with the optimized mana -= 3 syntax.
mana = 14
casts = 0
while mana > 3
mana -= 3
casts += 1
end
puts "You casted your spell #{casts} times and have #{mana} mana remaining."
⇩
You casted your spell 4 times and have 2 mana remaining.
Until
"I will love you until my dying day." Moulin Rouge: Come What May
Referencing a sappy line from a musical could be my highest achievement yet. You're too far in the book to stop now. It's all vampires and teen angst from here. I can see it now: "Programming book is #1 New York Times Bestseller!" What's that? It needs more magic you say? Okay, let's do this.
num = 1
until num == 5
print num
puts ": We're in the loop."
num += 1
end
⇩
1: We're in the loop.
2: We're in the loop.
3: We're in the loop.
4: We're in the loop.
For
What if you know exactly how many times you're going to loop? That's what this is for:
for num in 1..5
print num
end
⇩
12345
Recall our discussion earlier on range selection. As a reminder, we can exclude the last element by using three dots.
for num in 1...5
print num
end
⇩
1234