Sha256: 904c8f15e3c450c0c56d2215fa78d51d46109196146dd87ec9fc3ab344cf39b8

Contents?: true

Size: 504 Bytes

Versions: 1

Compression:

Stored size: 504 Bytes

Contents

require "luhn/version"

class Numeric
  def luhn
    digits = self.to_s.chars.map(&:to_i)
    sum = digits.reverse.each_with_index.map{ |x, i| i.even? ? (x * 2).divmod(10).inject(:+) : x }.reverse.inject(:+)
    (10 - sum % 10) % 10
  end

  def luhn?
    self.div(10).luhn == (self % 10)
  end

  def luhn!
    self * 10 + luhn
  end
end

class String
  def luhn
    self.gsub(/\D+/, '').to_i.luhn.to_s
  end

  def luhn?
    self.gsub(/\D+/, '').to_i.luhn?
  end

  def luhn!
    self + luhn
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
moeffju-luhn-0.1.3 lib/luhn.rb