From 93325ba46962d04e4e013f56c4e7b1daeed53398 Mon Sep 17 00:00:00 2001 From: HardikPurohit Date: Tue, 24 Jan 2017 09:58:01 +0530 Subject: [PATCH] Luhn --- luhn.rb | 45 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 luhn.rb diff --git a/luhn.rb b/luhn.rb new file mode 100644 index 0000000..5fe5040 --- /dev/null +++ b/luhn.rb @@ -0,0 +1,45 @@ +class Luhn + def initialize(num) + @number = num + end + def addends + temp_loop = @number + @result_chunks = [] + count = 1 + while temp_loop > 0 + digit_chunk = temp_loop % 10 + if count % 2 == 0 + check_9 = digit_chunk * 2 + if check_9 > 9 + @result_chunks << (check_9 - 9) + else + @result_chunks << check_9 + end + else + @result_chunks << digit_chunk + end + temp_loop = temp_loop / 10 + count += 1 + end + @result_chunks.reverse! + end + def checksum + addends + @sum_array = @result_chunks.inject(&:+) + @sum_array + end + def valid? + checksum + if @sum_array % 10 == 0 + true + else + false + end + end + def self.create(number) + arr = Luhn.new(number).addends + new_sum = 0 + number = number * 10 + (10 - Luhn.new(number * 10).checksum) % 10 + number + end +end