Learn Ruby the Hard Way – Exercise 3 Numbers and Math

Here is my work for Exercise 3.

Exercise 3 Code
Exercise 3 Code
Exercise 3 Output
Exercise 3 Output

Study Drills:
1. Above each line, use the # to write a comment to yourself explaining what the line does.

Commented Code for Exercise 3
Commented Code for Exercise 3

2. Remember in Exercise 0 when you started Ruby? Start Ruby this way again and using the math operators, use Ruby as a calculator.

I typed irb in Terminal to start interactive Ruby. Here are some math calculations I did. I played around with floating point numbers and integers. I also used the comparison operators, less than and greater than, to compare results of math calculations.

Math calculations in Ruby
Math calculations in Ruby

3. Notice the math seems “wrong”? There are no fractions, only whole numbers. You need to use a “floating point” number, which is a number with a decimal point, as in 10.5, or 0.89, or even 3.0.
Yes, the math seems “wrong” because 3 / 2 is 1 in Ruby. However, 3.0 / 2 is 1.5!


4. Rewrite ex3.rb to use floating point numbers so it’s more accurate. 20.0 is floating point.

Exercise 3 with floating point numbers
Exercise 3 with floating point numbers

For Study Drill #4, I changed one integer in each calculation into a float. I could do this because mathematical calculations with float objects and others return float objects. From the Ruby documentation, we see that a float object added to other returns a new float object. The same goes for subtraction, division, multiplication, modulo operation. By changing one of our integers into a float (For example on line 23, 3 + 2 is changed into 3.0 + 2), we get as the result 5.0 which is a float object.

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s