In this exercise you’ll learn how to effectively perform calculations on fractions in Ruby, including how you can build a method that returns a fraction.
Summary
Build a program that can perform calculations on two fractions and output the value in a string based fraction format.
Exercise File
Exercise Description
The program should be able to take three arguments (two fractions and an operator), passed in as strings, accurately perform calculations on them, and return the result in a string based fraction format.
Sample Input
"1/3", "2/4", "*"
Sample Output
"1/6"
Real World Usage
Being able to perform calculations on complex numbers is critical in a number of scenarios. This particular exercise also allows you to practice proper code organization strategies so that you can write clean code that’s easy to read and more practical to scale in the future.
Solution
Can be found on the solutions branch on github.
Hi Jordan,
I am pretty new to Ruby. I worked through this exercise and the test passed successfully…but what would I do if I wanted to run this program from the terminal and see the result either in a file or on the screen? I tried the print String(final_result) but that didn’t seem to do it.
Thanks,
Dan
Hi Dan!
You could just put this line at the bottom of your code which just calls the method fraction_calculator.
puts fraction_calculator(‘1/9’, ‘1/8’, ‘/’)
You can still use Rspec from the command line but I
put this line just above that and run it with ruby 9.rb
system ‘rspec 9.rb’ if __FILE__ == $PROGRAM_NAME
I’m using VSCode with a code runner extension so I do this with all these exercises. That way I don’t have to open a command line.
But here’s my output from Rspec on the command line.
8/9
.
Finished in 0.014 seconds (files took 0.36602 seconds to load)
1 example, 0 failures
Did you want to show it as a string? It is with puts which means put string so you don’t see the quotation marks. If you want those just add them to the front and back of that string.
Enjoy!