Skip to content

Instantly share code, notes, and snippets.

@falonofthetower
Created October 22, 2015 05:59
Show Gist options
  • Save falonofthetower/e0fcc2d5d138b4ccc3f0 to your computer and use it in GitHub Desktop.
Save falonofthetower/e0fcc2d5d138b4ccc3f0 to your computer and use it in GitHub Desktop.
require 'io/console'
def read_char
STDIN.echo = false
STDIN.raw!
input = STDIN.getc.chr
if input == "\e" then
input << STDIN.read_nonblock(3) rescue nil
input << STDIN.read_nonblock(2) rescue nil
end
ensure
STDIN.echo = true
STDIN.cooked!
return input
end
def perform_calculation(num1, op, num2)
num1.to_f.send(op, num2.to_f)
end
def is_numeric?(user_input)
user_input.to_i.to_s == user_input || user_input.to_f.to_s == user_input
end
def say(message)
puts "=>#{message}"
end
puts "A simple calculator which can perform addition, subtraction, and multiplication
on two values: "
puts "Values can include positives, negatives, and decimals"
def get_input(instance)
begin
puts "Enter your #{instance} value: "
value = gets.chomp
end until is_numeric?(value)
return value
end
value_1 = get_input("first")
value_2 = get_input("second")
puts "Enter a valid operator to perform a calculation (+ - or *): Press Control-C to quit"
def collect_operator(num_1,num_2)
case read_char
when "\-"
operator = "-"
puts operator
say "#{perform_calculation(num_1,operator,num_2)}"
when "\+"
operator = "+"
puts operator
say "#{perform_calculation(num_1,operator,num_2)}"
when "\*"
operator = "*"
puts operator
say "#{perform_calculation(num_1,operator,num_2)}"
when "\u0003"
puts "CONTROL-C"
exit 0
else
nil
end
end
collect_operator(value_1,value_2) while(true)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment