Skip to content

Instantly share code, notes, and snippets.

@selman
Created November 3, 2011 14:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save selman/1336663 to your computer and use it in GitHub Desktop.
Save selman/1336663 to your computer and use it in GitHub Desktop.
# http://en.wikipedia.org/wiki/Reverse_Polish_notation
# {method => arity} lookup hash of Float intance methods
METHOD_ARITY = Float.instance_methods(false).inject({}) {|ma, (m, _)|
ma[m] = 0.0.method(m).arity; ma}
def rpn str
str.split(/\s+/).inject([]) do |s, t|
m = t.to_sym
s << case METHOD_ARITY[m]
when 0, -1 # no or optional parameter
x = s.pop
x.send(m)
when 1 # infix operations like +, *
y, x = s.pop, s.pop
x.send(m, y)
else # it's a float number
t.to_f
end
end.pop # last member is the calculation
end
rpns = [
'10 4 3 + 2 * -', # -4.0
'5 1 2 + 4 * + 3', # 3.0
'43.2425 0.5 **', # 6.575902979819578
'-3 5 / abs' # 0.6
]
ARGV.empty? ? rpns.each {|x| puts rpn(x)} : ARGV.each {|x| puts rpn(x)}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment