Wednesday, June 20, 2007

Recursion in Ruby

Calculate x to the power of y using recursion.

def test(x, y)
if (y == 0)
return 1
else
test(x, y-1) * x
end
end

puts test(2,3)

This was a interesting question during the interview. I never understood recursion. The interviewer skillfully provided some clues for me to figure this one out myself. I wrote down some sample values for x and y in a tabular format. Worked through the problem and surprisingly come up with the right answer!

1 comment:

  1. I think the more web-centric your programming experience is, the less likely it is to run into recursion, or even the need for it. It came up more often back in my C/C++ days, and even a couple times during my "dark period" as a Perl debugger for reporting scripts :)

    I just wrote an article that shows a couple more examples of recursive methods, as they'd be applied to nested comments in a rails app:

    Recursion and Nested Comments in Rails

    If you get a chance, check it out.

    Thanks!

    ReplyDelete