Created
October 9, 2020 17:49
-
-
Save julian-a-avar-c/284c7fdba5adb5514f160f11fe87941a to your computer and use it in GitHub Desktop.
Console Calculator 2000
This file contains 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
# could be shorter or better implemented, but this'll do for now :) | |
class String | |
def is_numeric? | |
Rational(self) != nil rescue false | |
end | |
end | |
def parse(input) | |
if input.kind_of? String | |
if input.is_numeric? | |
input.to_r | |
else | |
test_validity(input) | |
end | |
elsif input.kind_of? Array | |
input.each do |inner| | |
operations = ["-", "+", "/", "*"] | |
operations.each do |operation| | |
if inner.include? operation | |
return inner\ | |
.split(operation)\ | |
.map { |e| parse(e) }\ | |
.reduce do |a, b| | |
case operation | |
when "-" then a - b | |
when "+" then a + b | |
when "/" then a / b | |
when "*" then a * b | |
end | |
end | |
end | |
end | |
return "invalid operation sequence detected, please use NONONON... sequence, (N)umber, (O)peration, it must end with a number" | |
end | |
end | |
end | |
def test_validity(input) | |
if input =~ /[\d\+\-\*\/ ]/ | |
parse([input]) | |
else | |
"input is invalid, non-number or unidentified characters detected" | |
end | |
end | |
def main | |
puts "Welcome to Console Calculator 2000" | |
prompt = "> " | |
while true | |
output = "" | |
print prompt | |
input = gets.chomp | |
parsed_input = parse(input) | |
parsed_input = parsed_input.to_f.to_s if parsed_input.kind_of? Numeric | |
output += parsed_input | |
puts "\u001b[1000D#{output}" | |
end | |
end | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment