Reputation: 25
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?
Upvotes: 0
Views: 215
Reputation: 16506
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.
Upvotes: 2