Created
August 14, 2021 20:33
-
-
Save d4vsanchez/6682b1d81b9312b264722a1fff76b768 to your computer and use it in GitHub Desktop.
Simple calculator done for The Complete Ruby on Rails Developer Course
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
module CalculatorStrategy | |
def calculate(number_a, number_b) | |
raise "Not implemented" | |
end | |
end | |
class AdditionStrategy | |
include CalculatorStrategy | |
def calculate(number_a, number_b) | |
number_a + number_b | |
end | |
end | |
class MultiplicationStrategy | |
include CalculatorStrategy | |
def calculate(number_a, number_b) | |
number_a * number_a | |
end | |
end | |
class DivisionStrategy | |
include CalculatorStrategy | |
def calculate(number_a, number_b) | |
number_a / number_b | |
end | |
end | |
class SubtractionStrategy | |
include CalculatorStrategy | |
def calculate(number_a, number_b) | |
number_a - number_b | |
end | |
end | |
class Calculator | |
def set_strategy(new_strategy) | |
@strategy = new_strategy | |
end | |
def calculate(number_a, number_b) | |
@strategy.calculate(number_a.to_i, number_b.to_i) | |
end | |
end | |
class CalculatorPresenter | |
def initialize(engine) | |
@engine = engine | |
end | |
def get_strategy | |
strategies = { | |
1 => MultiplicationStrategy, | |
2 => AdditionStrategy, | |
3 => SubtractionStrategy, | |
4 => DivisionStrategy, | |
} | |
strategies[@operation].new | |
end | |
def calculate_result | |
@engine.set_strategy(get_strategy) | |
@engine.calculate(@first_number, @second_number) | |
end | |
def present | |
puts "Simple calculator" | |
20.times { print "-" } | |
puts | |
puts "Enter the first number" | |
@first_number = gets.chomp.to_i | |
puts "Enter the second number" | |
@second_number = gets.chomp.to_i | |
puts "Select the operation you'd want to make:" | |
puts "\t1. Multiplication" | |
puts "\t2. Addition" | |
puts "\t3. Subtraction" | |
puts "\t4. Division" | |
@operation = gets.chomp.to_i | |
20.times { print "-" } | |
puts | |
puts "Result is: #{calculate_result}" | |
end | |
end | |
calculator = CalculatorPresenter.new(Calculator.new) | |
calculator.present |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment