maryanne maryanne - 2 years ago 111
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)

But if I check

puts twenty_one?(19, 2)

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

Answer Source

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 }

# more condensed version
def twenty_one? (*arr) 

twenty_one?(19, 2)
#=> true
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download