2012-10-04 141 views
-1

我試圖做一個酒杯仿真,下面是代碼...NoMethodError:未定義的方法「打」爲

one_suit = [2,3,4,5,6,7,8,9,10,10,10,10,11]; #the value of the cards for blackjack 
full_deck = one_suit*4; #clubs, diamonds, hearts and spades 
$deck = full_deck; #start off the game with a full deck 

class Player 
    attr_accessor :ace_count 
    attr_accessor :hand_value 

    def initialize(ace_count,hand_value) 
    @ace_count = ace_count; 
    @hand_value = hand_value; 
    end 

    def self.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 

end 

player1 = Player.new(0,0); 
player1.hit; 

然而,當我運行它,我得到以下的輸出:

NoMethodError: undefined method `hit' for # (root) at C:\Users\Ernst\Documents\JRuby\blackjack.rb:30

我在做什麼錯?該方法在類中定義。

回答

2

命中是一個類的方法。

如何用對象調用它?

當您編寫self。方法時,它被定義爲一個類方法。

要寫入對象或實例方法只是

使用def method .. end

你的情況

def hit 
## remove `self` identifier from the attributes. 
## e.g. ace_count += 1; 
end 

如果你想調用類的方法,你可以使用

Player.hit不是player_obj.hit

但我想你的需要是調用對象/實例方法,你可以通過刪除self標識符來完成。

+0

非常感謝! –

+0

希望你明白這個錯誤。 –

相關問題