Skip to content

Instantly share code, notes, and snippets.

@rodloboz
Created April 23, 2018 11:55
Show Gist options
  • Save rodloboz/bfbfafc6339d4529a63b65119f71c412 to your computer and use it in GitHub Desktop.
Save rodloboz/bfbfafc6339d4529a63b65119f71c412 to your computer and use it in GitHub Desktop.
def calculate(first_number, second_number, operator)
case operator
when "+"
first_number + second_number
when "-"
first_number - second_number
when "*"
first_number * second_number
when "/"
first_number / second_number
end
# Same as above
# if operator == "+"
# first_number + second_number
# elsif operator == "-"
# first_number - second_number
# elsif operator == "*"
# first_number * second_number
# elsif operator == "/"
# first_number / second_number
# end
end
# As the user for a number
# check if input valid
# Store the number given by the user
# As the user for another number
# Store the second number given by the user
# Ask the user for the type of operation
# Store the type of operation
# Execute the operation (+ - / *)
# Show/display result on screen
# ask user if they want to continue
# REGEXP to validate numbers input
# /\A\d+\Z/
# REG to validate operator input
# /\A[+-\/*]\Z/
require_relative "calculator.rb"
require 'pry-byebug'
choice = "yes"
loop do
puts "Enter first number:"
print "> "
first_number = gets.chomp
until first_number =~ /\A\d+\Z/
puts "Please type in a valid number:"
print "> "
first_number = gets.chomp
end
puts "Enter second number:"
print "> "
second_number = gets.chomp
until second_number =~ /\A\d+\Z/
puts "Please type in a valid number:"
print "> "
second_number = gets.chomp
end
puts "Choose operation [+][-][*][/]"
operator = gets.chomp
until operator =~ /\A[+-\/*]\Z/
puts "Please choose a valid operator: [+][-][*][/]"
print "> "
operator = gets.chomp
end
result = calculate(first_number.to_i, second_number.to_i, operator)
puts "Result: #{result}"
puts "Do you want to continue? (type 'quit')"
choice = gets.chomp
break if choice == "quit"
end
puts "Quitting... Goodbye!!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment