Despite not being super excited about maths in general, I was looking forward to working with numbers in Ruby. Having made a few small projects with JavaScript, I can appreciate how essential it is that I get to grips with this stuff to make things go more smoothly when I start writing more complex code.
Floats & Integers are two types of numbers. Read a short explanation here. Integers are whole numbers [3, 75, 40000000000000, etc,] and floats are floating-decimal numbers and that just means that they have a decimal point, even if there’s just a zero behind it [ 4.5, 7.37, 3.1415926535…] If you’re doing maths in your program, you should probably add the .to_f method to one of the numbers [turning the number into a float,] or make one of the numbers a decimal number by adding .0 to the end. Without making use of one of those, Ruby will only produce a nice round number – fine for very simple equations, but by ensuring that the result is a float you’re also making sure your expression is accurate- nothing like finding out your code doesn’t work because a number was rounded up! Just one of the numbers in the equation has to be a decimal number or float for Ruby to produce a result with a decimal number, and you can call the .to_f method on a number or variable. If the result of an expression uses integers, and there’s some rounding to get the result, calling .to_f on the resulting variable will not re-run the equation to give you an accurate result, it’ll simply make the rounded number into a float, with a zero behind the decimal. Have some time? Want to nerd out a little over some maths stuff? Read this: Floating-Point Arithmetic.
Finding out if a number is odd or even in Ruby is really easy: the .odd? and .even? methods are built in.
To generate a random number, Ruby has another built in method. Calling rand without any arguments will produce a number between 0 and 1, and calling rand(x) will produce an integer between 0 up to [but not including] x.
Spending some time looking at maths in Ruby makes me realise how slick and user-friendly Ruby is as a language. I know that, like any language, Ruby has quirks and weird bits, but it’s also really motivating to see how easy Ruby makes it to do these things.