2

I am trying to print out individual elements of a array using printf, this is what I have:

printf("\nCard %d: %s\t%d\t%s\t%s\n ", cardNum,card[0],card[1],card[2],card[3]) 

This doesn't really work, well, sort of, it gives me an error like this:

undefined method `[]' for nil:NilClass (NoMethodError) 

I am really confused on how to do this Ruby, Googled for a while but still couldn't figure out...

Thanks in advance!

2 Answers 2

2

This has nothing to do with printf at all. You are calling the [] method on the object referenced by the variable card, but that object is the nil object which doesn't have a [] method.

In other words: cards isn't an array at all, it is nil.

Sign up to request clarification or add additional context in comments.

Comments

0

printf is the traditional C way of doing this, but there's a shorthand that's more convenient:

card = %w[ KD 2C 4D 9S ] card_num = 1 puts "\nCard %d: %s\t%s\t%s\t%s\n " % [ card_num ] + card 

But even better:

puts "\nCard %d: %s\t%s\n " % [ card_num, card.join("\t") ] 

The error you're getting relates to card being nil, which usually means it's undefined.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.