2

I'm very new to Ruby and I'm trying to use math symbols that are stored in an array as strings to perform math. This is for a Reverse Polish Notation calculator I'm working on. For example:

var = ['1','2','+']

I've puzzled through enough regular expressions to figure out how to differentiate numbers from non-numbers in an if statement, but I'm trying to figure out how I could make the following work to produce -1.

var[0]  var[2] var[1]   #=>   1 - 2 

Does anyone know how to change the string '-' back into the math symbol?

1
  • You cannot do it. "Math symbol" is not a Ruby object. In other words, there is no such thing within Ruby code. Commented Aug 21, 2013 at 6:07

2 Answers 2

4
'1'.to_i.send('-', '2'.to_i)
# => -1 

send calls the first argument as a method on the object, with the remaining arguments as parameters.

Sign up to request clarification or add additional context in comments.

Comments

1

One way to do this is using the eval function

result = eval "#{var[0]} #{var[2]} #{var[1]}"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.