2

I've problem returning value from recursive function.

def ask_question(question)
    print question
    answer = STDIN.gets.chomp

    ask_question question if answer.empty?
    return answer
end

The first time the answer is returned properly but I got empty string in next calls. Why is that?

2 Answers 2

7

That is because you aren't returning the value returned by your recursive calls to ask_question.

def ask_question(question)
    print question
    answer = STDIN.gets.chomp
    answer = ask_question question if answer.empty?
    return answer;
end

All you were doing is returning the first user input value (in your case an empty string) when the method was done.

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

Comments

1

Your code does not work because the variable answer you return it's always the one in the first iteration (each call has its own local scope). So a possible solution is:

def ask_question(question)
    print question
    answer = STDIN.gets.chomp
    answer.empty? ? ask_question(question) : answer
end

Note though that this recursive construction is fine with languages that support tail-call optimization, but Ruby does not force it, so it will usually create a new stack frame for each iteration and eventually it will blow. I'd recommend looping, for example:

def ask_question(question)
  loop do 
    print question
    answer = STDIN.gets.chomp
    break answer unless answer.empty?
  end
end

2 Comments

To prove @tokland's point, if you run your program and hit enter a few times, then hit ctrl+c (for *nix), you'll see a stack trace proportionate to the number of times you hit enter.
good point, @jeremy. You can also run in a UNIX box "yes '' | ruby script.rb" and eventually get a "stack level too deep (SystemStackError)".

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.