Skip to content

Instantly share code, notes, and snippets.

@turbod
Created December 20, 2022 13:14
Show Gist options
  • Save turbod/ba5b09a4135a0d9846fc4c57b2a359e9 to your computer and use it in GitHub Desktop.
Save turbod/ba5b09a4135a0d9846fc4c57b2a359e9 to your computer and use it in GitHub Desktop.
Simple calculator in ruby
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