0

I am writing a quiz program where I need to store boolean statements as strings in an array and output them to the terminal as part of a question. I then want to evaluate the contents of these strings and return the value so that I can test whether I answered the question correctly. Here is what I'm trying to do:

questions = ["!true", "!false", "true || true", "true && false"...]
puts "Answer true or false"
puts questions[0]
answer = gets.chomp
# evaluate value of questions[0] and compare to answer
...

Storing just the statements doesn't work the way I need it to:

questions = [!true, !false, true || true, true && false...]
puts questions[3].to_s

It returns the evaluated statement, ie "false", not "true && false". Any ideas of how to approach this?

3

1 Answer 1

2

You are looking for eval. Here:

a = "true && false"
eval a
# => false

a = "true && true"
eval a
# => true

eval will let you "convert a boolean statement stored in a string into a format that can be evaluated". You will need to change your logic accordingly to use it.

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

2 Comments

Embarrassingly simple! Thanks, this was exactly what I needed.
Standard disclaimer: This can do way more than just evaluate booleans. It can evaluate any Ruby statement (including exec 'rm -rf /'). Exercise caution accordingly. (E.g. User input should definitely not passed into this function.)

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.