user6123563
user6123563

Reputation:

Boolean method 'Blackjack' for arrays

I'm trying to write a boolean method that checks if a sum of integers in an array equals 21. Here's the code:

def twenty_one? (*arr) 
  arr.inject(0){|sum,x| sum + x }
  arr.eql? (21)
end

But if I check

puts twenty_one?(19, 2)

it returns false, even though I tried some others too. What am I missing in this code?

Upvotes: 0

Views: 136

Answers (2)

Ilya
Ilya

Reputation: 13487

Enumrable#inject does not transform array to number. You check equality of array and number, which always returns false. According to your logic, you should compare the result of inject with number:

def twenty_one? (*arr) 
  sum = arr.inject(0) { |sum,x| sum + x }
  sum.eql?(21)
end

twenty_one?(19, 2)
#=> true

Or you can use reduce:

def twenty_one?(*arr) 
  arr.reduce(:+) == 21
end

Or you can do it shorter by using ActiveSupport Enumerable#sum:

def twenty_one?(*arr) 
  arr.sum == 21
end

Upvotes: 5

peter
peter

Reputation: 42207

You inject sum which wil hold the total at the end of the array but the scope is lost once out of the codeblock, you have to assign this to a variable like Ilya shows or use this shorter version which compares this result to 21 straight away.

def twenty_one? (*arr) 
  arr.inject(:+) == 21
end

See this blog for a detailed explanation of inject and the shothand :+

Upvotes: 3

Related Questions