Ruby as a calculator
Ruby calculates with +, -, * (times) and / (divided by). Run the cell – and feel free to change the numbers:
3 + 4Everything after # is a comment – Ruby ignores it. Comments are notes for humans (and foxes):
5 * 5 # five times fiveMultiplication and division come before addition and subtraction, just like at school, and parentheses go first. Two new signs join in: ** means “to the power of”, and % gives the remainder of a division (17 divided by 5 is 3, remainder 2):
puts 3 * 10 - 2 # times before minus: 28
puts 3 * (10 - 2) # parentheses first: 24
puts 2 ** 10 # 2 to the power of 10
puts 17 % 5 # the remainder of 17 / 5And now a surprise that trips up almost everyone once:
7 / 2=> 3? Ruby knows two kinds of numbers: whole numbers (Integer) like 7 and decimal numbers (Float) like 3.5 – written with a point. Divide a whole number by a whole number and Ruby divides whole numbers too: the remainder is simply dropped. As soon as one of the two is a Float, you get the exact result:
7 / 2.0In Ruby numbers are objects, and objects have methods: abilities you call with a dot. A few useful ones – and since a number in Ruby may grow as large as it needs to, 2 ** 100 is exact down to the last digit:
puts 3.7.round # rounding: 4
puts 7.fdiv(2) # dividing with decimals: 3.5
puts 10.even? # an even number? true
puts 2 ** 100 # no upper limit
1_000_000 + 1 # _ makes big numbers readableround also takes decimal places: (10 / 3.0).round(2) gives 3.33. Try it above! And should you ever meet a result like 0.30000000000000004: decimal numbers are not quite exact inside a computer – why, and what to do about money instead, is shown in lesson 64.
12.75. (Don't compute it yourself – that's the whole point! And remember 7 / 2…)77, store it in fahrenheit. And 100 °F back to Celsius: minus 32, times 5, divided by 9 – rounded to one decimal, 37.8, in celsius. Mind the whole-number trap when dividing!# fahrenheit = ... # 25 °C in Fahrenheit: times 9, divided by 5, plus 32
# celsius = ... # 100 °F in Celsius: minus 32, times 5, divided by 9 - rounded to one decimal