This course will be retired on June 1, 2025.
Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Start a free Courses trial
to watch this video
If we're going to multiply the quantity of widgets by the price to get the total, we're going to need to know how to do math operations. Really, math operations like addition, subtraction, multiplication, and division are central to almost any programming language, so most languages make them easy to do. Ruby is no exception.
Math operators take the values to their left and right and perform a math operation on them. The four most common operators add, subtract, multiply, or divide values.
+
-
*
/
Let's launch irb
, so we can try out a bunch of operations and immediately see the results.
$ irb
2.3.0 :001 > 2 + 3
=> 5
2.3.0 :002 > 12 - 4
=> 8
2.3.0 :003 > 5 * 8
=> 40
- For division operations, if you use two
Fixnum
/Integer
objects, any fractional part of the result will be truncated. Ensure that at least one of the operands is aFloat
for division operations.
2.3.0 :004 > 7 / 4
=> 1 # Should be 1.75, but gets truncated!
2.3.0 :005 > 7.0 / 4
=> 1.75
2.3.0 :006 > 7 / 4.0
=> 1.75
- Variables can be used in any part of the math operation.
2.3.0 :007 > number = 2
=> 2
2.3.0 :008 > number + 3
=> 5
2.3.0 :009 > 4 * number
=> 8
- Using a variable in a math operation leaves the value in that variable unchanged
2.3.0 :010 > number = 2
=> 2
2.3.0 :011 > number + 3
=> 5
2.3.0 :012 > number
=> 2
- You can do a math operation on a variable, and then assign the result back to that variable
2.3.0 :013 > number = 2
=> 2
2.3.0 :014 > number = number + 1
=> 3
2.3.0 :015 > number
=> 3
2.3.0 :016 > number = number + 1
=> 4
2.3.0 :017 > number
=> 4
2.3.0 :018 > number = number - 1
=> 3
2.3.0 :019 > number
=> 3
2.3.0 :020 > number = number * 2
=> 6
2.3.0 :021 > number
=> 6
2.3.0 :022 > number = number / 2.0
=> 3.0
2.3.0 :023 > number
=> 3.0
- Abbreviated assignment operators let you take the value in a variable and add to it, subtract from it, multiply it, or divide it, then reassign the result back to the same variable.
2.3.0 :001 > number = 2
=> 2
2.3.0 :002 > number += 1
=> 3
2.3.0 :003 > number
=> 3
2.3.0 :004 > number += 1
=> 4
2.3.0 :005 > number
=> 4
2.3.0 :006 > number -= 1
=> 3
2.3.0 :007 > number
=> 3
2.3.0 :008 > number *= 2
=> 6
2.3.0 :009 > number
=> 6
2.3.0 :010 > number /= 2.0
=> 3.0
2.3.0 :011 > number
=> 3.0
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up