Ruby 初心者レッスン課題 続き
ということで更に直す.
inject (fold) があることを忘れていた.
大分短くなった.(31 lines->21 lines)
#!/usr/bin/env ruby def rpn(expr) 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 calc(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 b = stack.pop a = stack.pop a.to_i.send(opr, b.to_i) end
別にGolf をしようとしている訳ではない.
(そもそもそういうレベルではない)