Reputation: 23
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?
Upvotes: 2
Views: 8849
Reputation: 67900
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
Upvotes: 1
Reputation: 22435
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.
Upvotes: 7