2

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!

3
  • 1
    "I've included the code of the start_game method." - no you haven't. Commented Apr 17, 2012 at 9:00
  • Oops! Forgot to edit that out. It's fixed now. I figured it wasn't worth including. Commented 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.) Commented Apr 17, 2012 at 10:03

1 Answer 1

1

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.

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

1 Comment

No problem! Enjoy learning Ruby - you picked a good language to learn programming with.

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.