Skip to content

Instantly share code, notes, and snippets.

@TimLang
Last active January 2, 2016 17:18
Show Gist options
  • Save TimLang/8335431 to your computer and use it in GitHub Desktop.
Save TimLang/8335431 to your computer and use it in GitHub Desktop.
simple arithmetic parser
# -*- encoding : utf-8 -*-
require 'debugger'
cal = lambda do |exp, stack=[]|
return exp if exp =~/^\d+$/
exp.scan(/((?:\d+)|[\*\+\/-]|(?:\((?:(?:\d)|[\*\+\/-])+\)))/) do |match|
word = match.first.to_s
if word =~ /^(\d+)$/
stack.unshift $1
elsif word =~ /^(\(\d+[\*\+\/-]\d+\))$/
return eval(exp)
elsif word =~ /^([\*\+\/-]{1})$/
stack.unshift $1
else
stack.unshift stack.pop.to_i.__send__(stack.pop, cal.call(word, stack).to_i)
end
end
end
puts cal.call("((9+19)-(31*2))+2")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment