I (think) I'm getting objects returned when I expect my array to have just 2 properties available

微笑、不失礼 提交于 2019-12-11 13:17:20

问题


Probably the worst way to ask a question, but I'm new and trying my best to explain my problem.

I'm implementing a Ruby Blackjack game. You can see the repo / source for what I have here: https://bitbucket.org/subem81/blackjack

This is the particular section of concern (kept in the "Hand" module which is included in the Dealer and Player classes using what I think are mixins):

def show_hand
    if self.class.to_s == 'Dealer'
        self.hand.each do |card|
            card.show_card
        end
    elsif self.class.to_s == 'Player'

    else
        puts "A Random person is showing their hand."
    end

end

Which calls the show_card() method for each Card object. Or so I thought. I keep getting no method errors on the card objects. Here is that error:

$ ruby blackjack.rb
Welcome to Mike's Blackjack.
blackjack.rb:35:in `block in show_hand': undefined method `show_card' for 
[# <Card:0x007fe504110918 @suit="Spades", @card_type="King">]:Array (NoMethodError)
from blackjack.rb:34:in `each'
from blackjack.rb:34:in `show_hand'
from blackjack.rb:21:in `setup_players'
from blackjack.rb:6:in `initialize'
from blackjack.rb:116:in `new'
from blackjack.rb:116:in `<main>'

回答1:


in Deck.give_card you are returning cards_sent via pop with an argument. This returns an array. So the dealer and player hands will be an array of arrays of cards. (pop without an argument returns a single item.)

From your error:

undefined method `show_card' for [# ]:Array

You can change:

            @dealer.hand << @deck.give_card
            @player.hand << @deck.give_card
            @dealer.hand << @deck.give_card
            @player.hand << @deck.give_card

to:

            @dealer.hand += @deck.give_card
            @player.hand += @deck.give_card
            @dealer.hand += @deck.give_card
            @player.hand += @deck.give_card

Or rename your give_card to give_cards and add a new give_card:

    def give_card
      @cards.pop
    end


来源:https://stackoverflow.com/questions/17689351/i-think-im-getting-objects-returned-when-i-expect-my-array-to-have-just-2-pro

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!