Ruby 初心者講座の続き

ということで,もういいよね.

#!/usr/bin/env ruby
# -*- mode: ruby; coding: utf-8; -*-

def rpn(expr)
  calc = Proc.new {|opr, stack|
    if stack.size < 2
      raise "not enough argument for operand (#{opr}) with [#{stack}]"
    end
    # => when stack : [... a, b], operand position : a opr b
    a, b = stack.slice!(-2, 2)
    a.to_i.send(opr, b.to_i)
  }
  result = expr.inject([]) {|r, e|
    r << (%w[+ - * /].include?(e) ? calc[e, r] : e)
  }
  unless result.size == 1
    raise "not enough operator. stack left [#{result}]"
  end
  result.shift.to_i
end

def main
  puts rpn(ARGV)
end

if File.basename(__FILE__) == File.basename($0)
  main
end

あと,Ruby 関西に行きたかったけどバッティングしていて,
今回は不可能でした.残念.