在Ruby中实现Luhn算法

Bri*_*ian 5 ruby

我一直在尝试在Ruby中实现Luhn算法.我一直在遵循以下步骤:

  • 公式根据其包含的校验位验证一个数字,该校验位通常附加到部分帐号以生成完整的帐号.此帐号必须通过以下测试:
    • 从最右边的校验位开始计数,然后向左移动,将每第二个数字的值加倍.
    • 将产品的数字(例如,10 = 1 + 0 = 1,14 = 1 + 4 = 5)与原始数字中的无数数字相加.
    • 如果总模数10等于0(如果总数以零结束)则该数字根据Luhn公式有效; 否则它无效.

http://en.wikipedia.org/wiki/Luhn_algorithm

这就是我想出的:

 def validCreditCard(cardNumber)
    sum = 0
    nums = cardNumber.to_s.split("")
    nums.insert(nums.size, "x")
    nums.reverse!
    nums.each_with_index do |n, i|
        if !n.eql?("x")
            sum += (i % 2 == 0) ? n.to_i : n.to_i * 2
        end
    end
    if (sum % 10) == 0
        return true
    else
        return false
    end
end
Run Code Online (Sandbox Code Playgroud)

但是,false每次测试时都会返回.我不确定我做错了什么.

Mic*_*ohl 20

这是一个有效的快速:

def credit_card_valid?(account_number)
  digits = account_number.chars.map(&:to_i)
  check = digits.pop

  sum = digits.reverse.each_slice(2).flat_map do |x, y|
    [(x * 2).divmod(10), y || 0]
  end.flatten.inject(:+)

  check.zero? ? sum % 10 == 0 : (10 - sum % 10) == check
end

credit_card_valid? "79927398713" #=> true
credit_card_valid? "79927398714" #=> false
Run Code Online (Sandbox Code Playgroud)

  • 使用`each_slice(2)`的问题是,如果account_number是一个奇数,当你尝试运行inject(:+)方法时,你会遇到问题. (5认同)
  • +1是一个非常惯用的实现.请注意,代替`scan(/./)`,您可以在Ruby 1.9+中使用`chars`.有关1.9+的信息,请参阅[`flat_map`](http://www.ruby-doc.org/core-1.9.3/Enumerable.html#method-i-flat_map) (3认同)

小智 10

我在运行上面的很多代码时遇到了问题,所以我继续开发了一个解决方案.下面是我的解决方案,以及测试代码,可以使用Ruby-cores AWESOME minitest库运行.

require "minitest"
require "minitest/autorun"

# Public: Validates number against Luhn 10 scheme
#
# Luhn Algo ripped from: http://en.wikipedia.org/wiki/Luhn_algorithm
# 1. From the rightmost digit, which is the check digit, moving left, double the value of every second digit; if product of this doubling operation is greater than 9 (e.g., 7 * 2 = 14).
# 2. Sum the digits of the products (e.g., 10: 1 + 0 = 1, 14: 1 + 4 = 5) together with the undoubled digits from the original number.
# 3. If the total modulo 10 is equal to 0 (if the total ends in zero) then the number is valid according to the Luhn formula; else it is not valid.
#
# Returns true or false
def luhn_valid?(cc_number)
  number = cc_number.
    gsub(/\D/, ''). # remove non-digits
    reverse  # read from right to left

  sum, i = 0, 0

  number.each_char do |ch|
    n = ch.to_i

    # Step 1
    n *= 2 if i.odd?

    # Step 2
    n = 1 + (n - 10) if n >= 10

    sum += n
    i   += 1
  end

  # Step 3
  (sum % 10).zero?
end

describe "Luhn Algorithm" do
  # Cards ripped from paypal: http://www.paypalobjects.com/en_US/vhelp/paypalmanager_help/credit_card_numbers.htm
  CC_NUMBERS = {
    "American Express" => "378282246310005",
    "American Express 2" => "371449635398431",
    "American Express Corporate" => "378734493671000",
    "Australian BankCard" => "5610591081018250",
    "Diners Club" => "30569309025904",
    "Diners Club 2" => "38520000023237",
    "Discover" => "6011111111111117",
    "Discover 2" => "6011000990139424",
    "JCB" => "3530111333300000",
    "JCB 2" => "3566002020360505",
    "MasterCard" => "5555555555554444",
    "MasterCard 2" => "5105105105105100",
    "Visa" => "4111111111111111",
    "Visa 2" => "4012888888881881",
    "Visa 3" => "4222222222222",
  }

  it "returns true for valid numbers" do
    assert CC_NUMBERS.values.all? { |number| luhn_valid?(number) }
  end

  it "returns false for invalid numbers" do
    CC_NUMBERS.values.each do |number|
      me_turn_bad = (number.to_i + 1).to_s
      refute luhn_valid?(me_turn_bad)
    end
  end
end
Run Code Online (Sandbox Code Playgroud)