Excitement! Now we can make interactive programs! In this one, type your name, and it will greet you:
puts 'Hello there, and what's your name?' |
name = gets |
puts 'Your name is ' + name + '? What a lovely name!' |
puts 'Pleased to meet you, ' + name + '. :)' |
Eek! I just ran it—I typed my name, and this is what happened:
<= | Hello there, and what's your name? |
=> | Chris |
<= | Your name is Chris |
? What a lovely name! | |
Pleased to meet you, Chris | |
. :) |
Hmmm...it looks like when I typed the letters C, h, r, i, and s and then pressed Enter, gets got all the letters in my name and the Enter! Fortunately, there’s a method that deals with just this sort of thing: chomp. It takes off any Enter characters hanging out at the end of your string. Let’s try that program again, but with chomp to help us this time:
puts 'Hello there, and what's your name?' |
name = gets.chomp |
puts 'Your name is ' + name + '? What a lovely name!' |
puts 'Pleased to meet you, ' + name + '. :)' |
<= | Hello there, and what's your name? |
=> | Chris |
<= | Your name is Chris? What a lovely name! |
Pleased to meet you, Chris. :) |
Much better! Notice that since name is pointing to gets.chomp, we don’t ever have to say name.chomp; name was already chomped. (Of course, if we did chomp it again, it wouldn’t do anything; it has no more Enter characters to chomp off. We could chomp on that string all day, and it wouldn’t change it. Like week-old bubble gum.)
18.188.228.180