Created
February 6, 2015 13:30
-
-
Save dylanerichards/618c32178468c21422bb to your computer and use it in GitHub Desktop.
Operators are just methods
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Operators are just methods. We can define and overwrite them just like any other. | |
| # By operators I mean things like +, -, *, /, and the list goes on. But these | |
| # are the most common. | |
| # | |
| # The goal for this program is to overwrite the subtract | |
| # method. For RightTriangle. The result should be a RightTriangle whose sides | |
| # are the result of performing subtraction (I know that's weird wording). | |
| RightTriangle = Struct.new(:leg1, :leg2, :hypotenuse) do | |
| # Overwrite - method | |
| def -(right_triangle) | |
| # Return a smaller RightTriangle | |
| RightTriangle.new(self.leg1 - right_triangle.leg1, self.leg2 - right_triangle.leg2) | |
| end | |
| end | |
| # Pythagoras stays the same | |
| class Pythagoras | |
| def self.theorem(right_triangle) | |
| hypotenuse = Math.sqrt((right_triangle.leg1 ** 2) + (right_triangle.leg2 ** 2)) | |
| right_triangle.hypotenuse = hypotenuse | |
| end | |
| end | |
| r = RightTriangle.new(3, 4) | |
| r2 = RightTriangle.new(1, 2) | |
| # Using our new method. This is the same as doing r - r2. Ruby implements what's | |
| # known as "syntactic sugar" that enables us to do things like this more elegantly. | |
| # Below is the dot notation for calling methods that we've been using all along. | |
| new_triangle = r.-(r2) | |
| Pythagoras.theorem(r) | |
| Pythagoras.theorem(r2) | |
| Pythagoras.theorem(new_triangle) | |
| p new_triangle | |
| p new_triangle.hypotenuse |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment