Skip to content

Instantly share code, notes, and snippets.

@mchail
Created October 3, 2014 23:35
Show Gist options
  • Save mchail/6d92a55adec898f12f71 to your computer and use it in GitHub Desktop.
Save mchail/6d92a55adec898f12f71 to your computer and use it in GitHub Desktop.
evaluate expression from string (and follow order of operations)
require 'json'
class StringCalc
def initialize(str)
@tokens = str.split('')
# puts @tokens.to_json
end
def run
tokens = reduce(@tokens, %w(/ *))
# puts tokens.to_json
tokens = reduce(tokens, %w(+ -))
# puts tokens.to_json
tokens.first.to_i
end
def reduce(tokens, ops)
new_tokens = []
iter = tokens.each
while true
begin
token1 = iter.next
# puts "token1 #{token1}"
if token1 =~ /\d/
new_tokens << token1
else
token2 = iter.next
# puts "token2 #{token2}"
if ops.include?(token1)
lhs = new_tokens.pop
# puts "lhs #{lhs}"
new_tokens << process(lhs, token1, token2)
else
new_tokens << token1 << token2
end
end
rescue StopIteration
return new_tokens
end
end
new_tokens
end
def process(lhs, op, rhs)
lhs.to_i.public_send(op, rhs.to_i).to_s
end
end
puts StringCalc.new("5+4*3").run
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment