문제

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