Skip to content

Instantly share code, notes, and snippets.

@jmeridth
Last active December 14, 2015 12:28
Show Gist options
  • Select an option

  • Save jmeridth/5086806 to your computer and use it in GitHub Desktop.

Select an option

Save jmeridth/5086806 to your computer and use it in GitHub Desktop.
Luhn Checksum implementation
#!/usr/bin/env ruby
# longer version with project structure and specs at https://github.com/jmeridth/luhn
require 'optparse'
def help
puts "Usage: luhn [positive number to validate]"
end
options = {}
opts = OptionParser.new do |opts|
opts.banner = "Luhn Checksum implementation"
opts.on("-h","-?","--help", "Display help") do
help
exit 0
end
end
begin
opts.parse!
rescue OptionParser::InvalidOption => e
help
exit 1
end
if ARGV.size != 1
help
exit 1
end
module Luhn
class CLI
def self.is_valid?(number)
odds = evens = 0
number.to_s.reverse.chars.each_slice(2) do |odd,even|
odds += odd.to_i
double = even.to_i * 2
if double >= 10
double = double.to_s.chars.map(&:to_i).inject(:+)
end
evens += double
end
(odds + evens) % 10 == 0
end
def self.run(number)
puts "With an input of #{number} the output would be:"
puts "#{number} is #{self.is_valid?(number) && 'valid' ||'not valid'}"
end
end
end
Luhn::CLI.run(ARGV[0])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment