Tuesday, June 14, 2011

Simple Ruby Credit Card Validator

This code below is a ruby implementation of Luhn Algorithm to validate credit cards numbers.


#!/usr/bin/env ruby

def is_valid(number)
x = number.split("")

i = 0

a = Array.new()

while (i < x.size) do
a.push(x[i].to_i*2)
i = i + 1
a.push(x[i].to_i)
i = i + 1
end
if (a.join("").split("").inject(0){|sum,item| sum + item.to_i} % 10 == 0)
return true
else
return false
end
end

puts is_valid(ARGV[0])

No comments: