Created
December 20, 2022 13:14
-
-
Save turbod/ba5b09a4135a0d9846fc4c57b2a359e9 to your computer and use it in GitHub Desktop.
Simple calculator in ruby
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
operation = "1 + 1 + 20 - 3 " | |
Kernel.eval operation | |
# 19 | |
raw_ops = operation.split /(\+|-)/ | |
ops = raw_ops.map { |raw_op| Integer(raw_op, exception: false) || raw_op } | |
# [1, "+", 1, "+", 20, "-", 3] | |
while ops.size > 1 | |
operator = ops.delete_at(1) | |
operand = ops.delete_at(1) | |
ops[0] = ops[0].send(operator, operand) | |
end | |
ops.first | |
# 19 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment