March 2009
Intermediate to advanced
194 pages
4h
English
The other two arithmetic methods are ** (exponentiation) and % (modulus). So if you want to say “five squared” in Ruby, you would 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 division by a number. So, for example, if you divide 7 by 3, you get 2 with a remainder of 1. Let’s see it working in a program:
puts 5**2 |
puts 5**0.5 |
puts 7/3 |
puts 7%3 |
puts 365%7 |
25 |
2.23606797749979 |
2 |
1 |
1 |
From that last line, we learn that a (nonleap) year has some number of weeks, plus one day. So if your birthday was on a Tuesday this year, it will be on a Wednesday next year. You can also use floats with the modulus method. Basically, ...