I'm just learning Ruby and programming in general. I'm working on a blackjack program as my first project. I have a method start_game that is called to start every new hand. The method is called and then calls itself again when the hand is over. Is this the correct way to do this? This seems to me like it would endlessly allocate memory every time the method is called. I'm not sure if this is something that garbage collection will handle or not. I feel like there's probably a better way to do this but can't figure it out. Thanks in advance!
-
1"I've included the code of the start_game method." - no you haven't.Andrew Grimm– Andrew Grimm2012-04-17 09:00:55 +00:00Commented Apr 17, 2012 at 9:00
-
Oops! Forgot to edit that out. It's fixed now. I figured it wasn't worth including.Kevin– Kevin2012-04-17 09:35:35 +00:00Commented Apr 17, 2012 at 9:35
-
It's almost always worth including some code - the trick is being able to include the relevant bits. If you're not sure I would err on the side of including too much (but don't go pasting in a whole pages long program for example, no one will read it.)Russell– Russell2012-04-17 10:03:49 +00:00Commented Apr 17, 2012 at 10:03
1 Answer
Calling a method recursively like this will eventually cause the stack to overflow (if enough hands are played, not sure how likely that is).
Unless, that is, tail-call optimisation prevents this from happening. This is a form of optimisation which can be applied to recursive method calls where the recursive call is always the last thing to be called in any run through the method. This basically converts the recursive call to a loop, so you don't end up adding to the stack each time round.
However, according to this question you can't rely on tail-call optimisation in Ruby. So I would rewrite your code a bit so start_game is called in a loop which tests some condition to decide if it should continue.