mardi 5 mai 2015

What's the best way search a Ruby Hash for key-value pairs matching a value and then changing that value?

I'm building a Blackjack game to better understand Ruby, and am trying to have users able to switch out values from a "hand." I store the deck as a Hash containing the deck and then scoring value like this :D8 => 8 where it's an eight of Diamonds worth eight points. Aces, because they can be either 1 or 11 get stored like this: :SA => "option."

I would like to be able to prompt the user to for a value or This is currently part of the code:

def checkAce
    if @player_hand.has_value?("option")

        puts "What do you want your aces to be worth? 11 or 1"

        ace_value = gets.chomp
        aces = @player_hand.find {|k, v| @player_hand[k] == "option"}

        if ace_value == "1" || ace_value == "11"
            aces.each { |k, v| aces[k] = ace_value }
        else 
            checkAce
        end 

        # merge back into hand 
        @player_hand.merge!(aces)

    else
        puts "No aces, so on to the main event." 
    end 
end

But this code doesn't work: first, the ace_value gives me a typeerror saying that symbol cannot be coerced into integer. And second, the @player_hand.merge!(aces) doesn't find a method. Any advice?

Aucun commentaire:

Enregistrer un commentaire