سؤال

I'm working on an RPN Calculator and think I'm almost there, except it's returning the expression not the solution.

def evaluate(expression)
  expression = expression.split

  operators = expression.select { |v| v =~ /\W/}
  operands  = expression.select { |v| v =~ /\d/}

  new_expression = operands.zip(operators)
  eval = new_expression.join
end

This should return -7:

puts evaluate('5 8 + 4 - 5 *')
#=> 5+8-4*5
هل كانت مفيدة؟

المحلول

eval = new_expression.join

This calls new_expression.join and stores the result in a local variable called eval. Since you never use that local variable, you could as well just have written:

new_expression.join

If it was your intention to call Ruby's eval method with the result of new_expression.join as its argument, you should remove the assignment operator:

eval new_expression.join

That said using eval to evaluate the expression is only a good idea if you're only ever evaluating trusted input.

نصائح أخرى

It does exactly what you've written, i. e. it makes variable eval with String given. Solution:

def evaluate(expression)
  expression = expression.split

  operators = expression.select { |v| v =~ /\W/}
  operands  = expression.select { |v| v =~ /\d/}

  new_expression = operands.zip(operators)
  eval new_expression.join
end

puts evaluate('5 8 + 4 - 5 *')

You are creating a local variable called eval, but you really want to call Kernel#eval with your expression as parameter like so:

eval operands.zip(operators).join
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top