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
print "Give me a number: "
number = gets.chomp.to_i

bigger = number * 100
puts "A bigger number is #{bigger}."

print "Give me another number: "
another = gets.chomp
number = another.to_i

smaller = number / 100
puts "A smaller number is #{smaller}."

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

  1. Try out the .to_f operation. What does .to_f do?
  2. 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.

Buy DRM-Free

When you buy directly from the author, Zed A. Shaw, you'll get a professional quality PDF and hours of HD Video, all DRM-free and yours to download.

$29.99

Buy Directly From The Author

Or, you can read Learn Ruby the Hard Way for free right here, video lectures not included.