Day 17: Continuing with Learning Ruby the Hard Way

Exercise 12: Prompting People for Numbers

Here is what I had to type:

And the result:

PS C:\ruby> ruby ex12.rb
Give me a number: 42
A bigger number is 4200.
Give me another number: 33
A smaller number is 0.

This builds on the gets.chomp from the last exercise. By adding .to_i to the method, it converts what is entered to an integer. The second number asked for is first done through gets.chomp and then converted to an integer with .to_i.

Study Drills:

1. Try out the .to_f operation. What does .to_f do?

So, I typed this:

and got this:

PS C:\ruby> ruby ex12.rb
Give me a number: 100
A bigger number is 10000.0.
Give me another number: 1000
A smaller number is 10.0.

Looks like it converts the number to a floating decimal!

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.

SO, this one was a bit weird. i tried originally to use:

PS C:\ruby> ruby studydrill12.rb
We can help you with paying the right tip! How much is your bill?
36.98
OK, so a typical tip is 20% of the bill. That means your tip would be $7.396. The total is $44.376.

This is great, but I want Ruby to do the rounding. After Googling for a bit I found .round() and changed the code to this:

and the result:

PS C:\ruby> ruby studydrill12.rb
We can help you with paying the right tip! How much is your bill?
36.98
OK, so a typical tip is 20% of the bill. That means your tip would be $7.4. The total is $44.38.

The only issue right now is that if you enter letters you get this:

PS C:\ruby> ruby studydrill12.rb
We can help you with paying the right tip! How much is your bill?
hi everyone
OK, so a typical tip is 20% of the bill. That means your tip would be $0.0. The total is $0.0.

So, I need to work on getting it to validate integers and not letters! Baby steps.

I am off to eat and will be back later!