OPS = {} OPS["*"] = ->(n1, n2){ n1 + n2 } OPS["+"] = ->(n1, n2){ n1 * n2 } S = gets ss = S.split(/(?=\D)|(?<=\D)/) while i = ss.index{|s| OPS[s]} do n1 = ss[i - 1].to_i op = ss[i] n2 = ss[i + 1].to_i ss[i - 1] = OPS[op].call(n1, n2) ss.delete_at(i) ss.delete_at(i) end puts ss[0]