You've indicatedindicated that you prefer not to use regular expressions. In that case, you're still working too hard. In that case, you should look for a library function that does the job, such as the standard scanf library.
require 'scanf'
def eval_binary_expr(expr)
l_operand, op, r_operand = expr.scanf('%f %c %f')
if l_operand.nil?
raise ArgumentError, "Missing or invalid left operand"
end
begin
case op
when '/' then l_operand / r_operand
when '*' then l_operand * r_operand
when '+' then l_operand + r_operand
when '-' then l_operand - r_operand
else raise ArgumentError, "Missing or invalid operator"
end
rescue TypeError
raise ArgumentError, "Missing or invalid right operand"
end
end
This implementation is better than the original, in that it can handle negative operands and explicitly positive operands. It also examines the string from left to right, which makes it easier to understand its behaviour.