nums nums - 4 months ago 8
Ruby Question

How to solve ruby string

I'm new to ruby, and I'm trying to make a simple calculator in which a user types in a simple problem (such as addition or subtraction) and the answer is returned. The problem is when the user types in a question, the question itself is being returned instead of the answer to that question.

puts "How many Questions?"
questions = gets.chomp.to_i

questions.times do |problem|
puts "question: "
problem = gets.chomp
puts "answer: #{problem}"
end

Answer

Inside your loop, instead of:

problem = gets.chomp
puts "answer: #{problem}"

Try this:

problem = gets.chomp
solved_problem = eval(problem)
puts "answer : #{solved_problem}"

eval will take care of interpreting your string as a Ruby instruction. But it's very messy, because anyone could write any Ruby program in your input and eval will make it run, so it's not safe at all.

If you only want to take care of simple operations, you can use a regex first to check if the input string looks like what you want:

problem_is_ok = (problem =~ /^\d+ *[+-] *\d+$/)

This will be true if the string starts with a number, followed by 0 to many spaces, followed by either a + or - sign, followed by 0 or more spaces, followed by another number and nothing else. Then you raise an error if this is not true.

Your loop now look like this:

questions.times do |problem|
    puts "question: "
    problem = gets.chomp
    problem_is_ok = (problem =~ /^\d+ *[+-] *\d+$/)
    if problem_is_ok
        puts "answer: #{eval(problem)}"
    else
        #I raise an error, but you might aswell just print it instead for your simple program
        raise ArgumentError("Can't compute this")
    end
end
Comments