Recursive algorithms in ruby