More Arithmetic

Learn to Program, Third Edition — by Chris Pine (32 / 116)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Fancy String Methods | TOC | Random Numbers 👉

You’ve already learned four arithmetic methods: +, -, *, and /. The other two arithmetic methods are ** (exponentiation) and % (modulus). So, if you want to say “five squared” in Ruby, you’d write it as 5**2. You can also use floats for your exponent; so, if you want the square root of 5, you could write 5**0.5.

The modulus method gives you the remainder after integer division. This might seem a bit bizarre, like integer division did at first, but integer division and modulus are particularly handy when used together. For example, suppose you have $7, and a bag of chips costs $3. Integer division tells you how many bags you can buy (7/3, which is 2), and modulus tells you how much money you’ll have left afterward (7%3, which is 1). Let’s see this working in a program:

​1: puts 5**2 
​2: puts 5**0.5
​3: puts 7/3
​4: puts 7%3
​5: puts 365%7
​<= 25
​ 2.23606797749979
​ 2
​ 1
​ 1

From that last line, you learn that a (non-leap) year has some number of weeks (how many? 365/7), plus one day. So, if your birthday was on a Tuesday this year, it’ll be on a Wednesday next year. You can also use floats with the modulus method. It works the only sensible way it could…but I’ll let you play around with that. (In twenty years of programming in Ruby, I don’t think I’ve ever used modulus with floats.)

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.