Skip to content

Instantly share code, notes, and snippets.

@cabron
Created July 9, 2012 15:42
Show Gist options
  • Select an option

  • Save cabron/3077228 to your computer and use it in GitHub Desktop.

Select an option

Save cabron/3077228 to your computer and use it in GitHub Desktop.
/r/dailyprogrammer #73 intermediate
#!/usr/bin/env ruby
class RPNError < ArgumentError
def initialize sym, stack
args = stack.reverse.map.with_index {|el, i|
"#{el}.#{sym} (#{i} for #{el.method(sym).arity})"
}.join(', ')
super "wrong number of arguments: #{args}"
end
end
stack = []
ARGV[0].scan(/(-?[0-9]+)|(self|true|false)|(\S+)/).each do |num, keyw, sym|
if num
stack.push num.to_i
elsif sym
args_n = nil
obj, i = stack.each.with_index.find {|el, i|
arity = el.method(sym).arity
args_n = stack.size - i - 1
arity < 0 ? (arity.abs-1 <= args_n) : (arity == args_n)
}
raise RPNError.new(sym, stack) unless obj
stack.push obj.send(sym, *stack.pop(args_n+1).drop(1))
else
stack.push({:self => stack, :true => true, :false => false}[keyw.to_sym])
end
end
puts "=> #{stack.first.inspect}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment