I am trying to build a 'blackjack' game using Ruby. The user is dealt a random card every time they input 'hit'. If they input 'stick' there are some other conditions but not relevant right now. The game is supposed to return the running total of their deck whilst they input 'hit'.
However, I am getting stuck ‘summing’ the running total of the users deck. Whenever I use .sum it says ‘Array can’t be coerced into integer’. I believe this is because you cannot ‘sum’ a nil value. I tried the below methods to try and get around this but no luck;
- .compact
- .inject(: )
- .reduce(: )
- .map { |n| n[nil] = 0}
Any pointers would be massively appreciated. Also, apologies. I know the code is not as efficient as it could be - I am still very new to this.
CODE
def score
kvpz = {
"two" => 2, "three" => 3, "four" => 4,
"five" => 5, "six" => 6, "seven" => 7,
"eight" => 8, "nine" => 9, "ten" => 10,
"jack" => 10, "queen" => 10, "king" => 10,
"ace" => 11
}
end
def random_card
cards = [
"two", "three", "four", "five", "six", "seven",
"eight", "nine", "ten", "jack", "queen", "king", "ace"
]
cards[rand(13)]
end
def move
total = []
while true do
puts "hit or stick"
input = gets.chomp
if input == "hit"
deck = [""]
deck.push(random_card)
total << deck.map { |n| score[n] }
puts total
elsif input == "stick" && total <= 21
puts "You scored: #{total}"
abort
elsif input == "stick" && total > 21
puts "You busted with: #{total}"
abort
end
end
end
def run_game
score
random_card
move
end
run_game
CodePudding user response:
It's because here you push an array into total
, not a number.
total << deck.map { |n| score[n] }
Ending up with total
containing array of arrays. And sum
method can not sum arrays. Try putting only numbers into total
array.
CodePudding user response:
Change total << deck.map { |n| score[n] }
to total = deck.map { |n| score[n].to_i }
to_i
here prevents nil
value (nil.to_i # => 0
)
=
just add (not nested) elements to total
array
total <= 21
-- here use total.sum <= 21
But if you don't need total
as array you can just initialize it as 0
(not []
) and then
total = deck.sum { |n| score[n].to_i }