Skip to content

Instantly share code, notes, and snippets.

@zh4ngx
Created October 8, 2013 06:31
Show Gist options
  • Save zh4ngx/6880395 to your computer and use it in GitHub Desktop.
Save zh4ngx/6880395 to your computer and use it in GitHub Desktop.
Functional-ish version of stack machine
$stack = []
def solution(s)
s.each_char do |c|
case c
when /[0-9]/
$stack.push c
puts c
when '+'
return -1 unless op_nums(lambda { |left, right| left + right })
when '*'
return -1 unless op_nums(lambda { |left, right| left * right })
end
end
return $stack.pop
end
def op_nums operation
left = $stack.pop
right = $stack.pop
if left and right
$stack.push operation.call(left.to_i, right.to_i)
else
false
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment