- Use Ruby math operations to build a calculator
- Define instance method
- Use the Ruby
Mathclass to call a method provided by Ruby
Calculators can be very useful devices in day-to-day activities. You've likely used a calculator to add up bills for this month or calculate the tip at a restaurant. We're going to take our arithmetic knowledge and put it to the test by writing functions that will do basic math calculations for us, just like we can see in IRB.
Fork and clone this repo and open lib/math.rb. You'll find a bunch of empty
methods that take numbers as arguments. Build the appropriate behavior for each
of the following methods:
addition- Build the methodadditionthat addsnum1tonum2and returns the result of this calculationsubtraction- Build the methodsubtractionthat subtractsnum1fromnum2and returns the result of this calculationmultiplication- Build the methodmultiplicationthat multipliesnum1fromnum2and returns the result of this calculationdivision- Build the methoddivisionthat dividesnum1intonum2and returns the result of this calculationmodulo- Build the methodmodulothat dividesnum1intonum2and gives us the remainder of this calculationsquare_root-- Build the methodsquare_rootthat finds the square root ofnumand returns the result
If a few places we've asked specific instances of data to run methods
(.class or .to_s) have come up in the Programming as Conversation series.
We call those instance methods. We're asking a given number, say 314 for
its .class (314.class #=> Integer).
But sometimes Ruby provides standard helpful functions as class methods. A
class method is like a utility method that's contained in a special namespace.
Let's say you needed to do some trigonometry. Ruby has you covered! You can use
Math.sin() to find the sine of an angle. Ruby also provides Math.sqrt as a
class method so that you can use Ruby's understanding of squares to help out.
The square_root method this lab requires you to write should use Math.sqrt.
This is scratching the surface of "Object-Oriented Programming." Helpful functions are available to instances and classes to help do work. There's a lot to say about this, but for the time being, we can use some class methods to help do some advanced mathematics.
Submit the lesson once all tests are passing.
Ruby gives us many operators that can be used to perform calculations. This is the tip of the iceberg--we can do so much more than simple arithmetic, however, these operations are the most common that a developer will encounter. Grasping the basics will get you very far!