Exercise 12: Prompting People for Numbers
You may have noticed in Exercise 11 that you were getting strings from the user. How do you get numbers? Type this code in to find out how.
1 2 3 4 5 6 7 8 9 10 11 12 |
What You Should See
$ ruby ex12.rb
Give me a number: 10
A bigger number is 1000.
Give me another number: 200
A smaller number is 2.
See how I can add a .to_i to the gets.chomp and it will convert to an integer? I can also save what gets.chomp returns, and call .to_i on that, as I did with number = another.to_i.
Study Drills
- Try out the .to_f operation. What does .to_f do?
- To play with .to_f more, make a small script that asks for some money and gives back 10% of it. If I give your script 103.4 (dollars), your script gives me back 10.34 in change.