maryanne maryanne - 7 months ago 20
Ruby Question

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?

Answer

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 result of inject with number:

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

# more condensed version
def twenty_one? (*arr) 
  arr.inject(:+).eql?(21)
end

twenty_one?(19, 2)
#=> true