Last active
January 2, 2016 17:18
-
-
Save TimLang/8335431 to your computer and use it in GitHub Desktop.
simple arithmetic parser
This file contains hidden or 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
| # -*- 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