In fact, if you subtract nine from any double over ten you will get the same sum.One way to put this to use is with a trivial lookup table, as Brad Ediger did: Skipping over the sum() and mysterious mapn() methods for now, just take in the usage of double_and_sum.Let's try one more, 4417 1234 5678 9112: Step 1: 8 4 2 7 2 2 6 4 10 6 14 8 18 1 2 2Step 2: 8 4 2 7 2 2 6 4 1 0 6 1 4 8 1 8 1 2 2 = 69Step 3: 69 % 10 ! This week's Ruby Quiz is to write a program that accepts a credit card number as a command-line argument.The program should print the card's type (or Unknown) as well a Valid/Invalid indication of whether or not the card passes the Luhn algorithm. The reason I ran it though is that I wanted to see how people approached the Luhn algorithm implementation. I'll leave it to him to explain his own solution, as punishment for the time it took me to puzzle it out.First, let's get the formality of a full solution out of the way.Here's some code from Drew Olson: As Drew shows, checking the type() is just a matter of verifying length and prefix against a known list. Drew bypasses the need for my crazy Regexp using a trick I'm always harping on: reverse the data.The card number is split() into digits and reverse()d as we have been seeing.
Check that for divisibility by ten and we have our answer.It's an easy enough process, but I found myself using an odd combination of Regexp and eval() when I was fiddling with it: I knew that was ugly and wanted to see how you guys would pretty it up. I had to print that Array inside of the inject() call during each iteration to see how it built up the answer.I do want to show you a slew of interesting tidbits though.The interesting part is that N is chosen from the arity of your provided block.If we ask for two at a time, we get two; ask for three and we get three: That's a pretty smart iterator, I say. Work has been rough this week and I need some down time.