Ruby 中的堆栈级别太深,试图随机抽取一张卡片 [英] Stack level too deep in Ruby trying to draw a random card

查看:72
本文介绍了Ruby 中的堆栈级别太深,试图随机抽取一张卡片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在运行下面的代码时遇到错误堆栈级别太深".如果选择的随机卡不在那里,它会选择另一张随机卡.我想我应该以某种方式尝试代码,但我不确定如何.有什么建议吗?

I'm getting an error "stack level too deep" running the code below. If the random card picked is not there it picks another random card. I suppose I should chance the code somehow, but I'm not sure how. Any suggestions?

   def hit 
    choice_of_card = rand($deck.length); #choose a random card out of the deck
    drawn_card = $deck[choice_of_card]; #draw that random card from the deck
    if drawn_card != 0 #if there is a card there 
     $deck[choice_of_card] = 0; #remove that card from the deck by making the space blank
     if drawn_card == 11 #if you draw an ace
      self.ace_count += 1;
     end 
     self.hand_value += drawn_card ;
    else hit; #if there is no card at that space then redraw (recursion)
    end
  end

推荐答案

我认为可以肯定地说是递归导致了错误.在我看来你不需要递归,你可以循环直到你得到 draw_card != 0,例如,

I think it's safe to say the recursion is causing the error. Seems to me you don't need recursion, you could just loop until you get drawn_card != 0, e.g.,

drawn_card = 0
while drawn_card == 0
  choice_of_card = rand($deck.length); #choose a random card out of the deck
  drawn_card = $deck[choice_of_card]; #draw that random card from the deck
end

这篇关于Ruby 中的堆栈级别太深,试图随机抽取一张卡片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆