Skip to content

Instantly share code, notes, and snippets.

@stefanosc
Created September 26, 2014 19:31
Show Gist options
  • Save stefanosc/13c82651547bf4a6fc24 to your computer and use it in GitHub Desktop.
Save stefanosc/13c82651547bf4a6fc24 to your computer and use it in GitHub Desktop.

Revisions

  1. Stefano Schiavi created this gist Sep 26, 2014.
    22 changes: 22 additions & 0 deletions cc
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,22 @@
    class RPNCalculator
    def evaluate(rpn_expr)
    begin
    count = 0
    result = rpn_expr.split(' ').each_with_object([]) do |item,arr|
    item.match(/(\A-?\d+\z)|(\A[\+\-\*]\z)/) do
    if $1
    count += 1
    arr << item.to_i
    else
    count -= 1
    raise ArgumentError.new("not enough digits!") if count < 1
    arr[-2..-1] = ( arr[-2].send(item, arr[-1]) )
    end
    end or raise ArgumentError.new("malformed RPN expression!")
    end
    count == 1 && result.first or raise ArgumentError.new("too many digits!")
    rescue ArgumentError => e
    e.message
    end
    end
    end