2014-01-26 7 views
0

저는 Ruby를 처음 접했고이 문제를 조사하기 위해 노력했습니다. 지금까지 코드가 있습니다. 사용자 개체 (user.deal_one (mydeck.deal_card))를 호출 할 때이 문제가있는 것 같지 않지만 딜러에서 호출 할 때이 오류가 발생합니다. 딜러 개체는 동일한 인스턴스 변수를 갖고 있는데 왜 '< <'메서드를 호출하는지 확신 할 수 없습니다. 여기 문제 이해 루비 오류 : 정의되지 않은 메서드`<< 'for nil : NilClass (NoMethodError)

전체 에러이다 blackjackOOP.rb : 32 : < < deal_one': undefined method에서 '닐의 경우 : NilClass (NoMethodError) blackjackOOP.rb에서 : 106 :'에서 '

class Deck 
    def initialize 
    @deck = [] 
    @suit = ["Clubs", "Diamonds", "Hearts", "Spades"] 
    @value = [2, 3, 4, 5, 6, 7, 8, 9, 10, "Jack", "Queen", "King", "Ace"] 
    @count = 0 

    @value.each do |x| 
     @suit.each do |y| 
     @deck[@count] = [x, y] 
     @count += 1 
     end 
    end 
    @deck.shuffle! 
    end 

    def deal_card 
    @card = [] 
    @card << @deck.pop 
    @card 
    end 

    def show_deck_size 
    puts @deck.size 
    end 
end 

module Hand 
    def deal_one(card) 
    @hand << card 
    end 

    def total 
    @total = 0 
    @hand.each do |card| 
     card.each do |val, suit| 
     if val == "Jack" || val == "Queen" || val == "King" 
      @total += 10 
     elsif val != "Ace" 
      @total += val 
     elsif val == "Ace" 
      if @total > 10 
      @total += 1 
      else 
      @total += 11 
      end 
     end 
     end 
    end 
    end 
end 

class Player 
    include Hand 

    def initialize(name) 
    @name = name 
    @hand = [] 
    end 

    def hit_stay 
    puts "#{@name} has #{show_hand} for a total of #{@total}" 
    end 

    def show_hand 
    @hand.each do |card| 
     card.each do |val, suit| 
     print "#{val} of #{suit} " 
     end 
    end 
    end 
end 

class Dealer 
    include Hand 

    def initalize 
    @name = "Dealer" 
    @hand = [] 
    end 
end 

def say(n) 
    puts "=> #{n}" 
end 



say("Hello would you like to play some blackjack? Great!") 
say("What is your name?") 
name = gets.chomp 

mydeck = Deck.new 
user = Player.new(name) 
dealer = Dealer.new 

say("Welcome #{name}! Let's play!") 


#deal hands to dealer and player 
user.deal_one(mydeck.deal_card) 
user.deal_one(mydeck.deal_card) 
dealer.deal_one(mydeck.deal_card) 
+2

도움이된다면 [답변을주십시오.] (http://stackoverflow.com/questions/21369303/issue-understanding-ruby-error-undef-method-for-nilnilclass-nomethod/21369424#21369424). –

답변

3

오타가 귀하의 딜러 클래스에.

def initalize을 작성했으며 def initialize이어야합니다.

+0

당신은 아주 좋은 눈을가집니다. :) Great +1 –

+0

@ArupRakshit 이런 식으로 물건을 찾는 방법은 그것을 치어 세우기 세션에 넣고 어떻게 보이는지 보입니다. Player.new 메서드를 호출 할 때 결과 객체는 Dealer.new 세션에서 생성 된 딜러 객체와 매우 다르게 보입니다. 무엇보다 두드러진 점은 dealer.hand가 초기화되지 않았기 때문입니다. 이로 인해 실제 오류가 발생할 수있는 곳은 거의 없습니다. – FlyingFoX

+0

나는 결코 사용하지 않았다. –

관련 문제