Created
February 23, 2012 03:05
-
-
Save kaochenlong/1889703 to your computer and use it in GitHub Desktop.
台灣公司統一編號判斷規則
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# encoding: utf-8 | |
def company_serial_no_checker(serial) | |
# 共八位,全部為數字型態 | |
at_least_8_digits = /^\d{8}$/ | |
return false unless at_least_8_digits.match(serial) | |
# 各數字分別乘以 1,2,1,2,1,2,4,1 | |
# 例:統一編號為 53212539 | |
# | |
# Step1 將統編每位數乘以一個固定數字固定值 | |
# 5 3 2 1 2 5 3 9 | |
# x 1 2 1 2 1 2 4 1 | |
# ================================ | |
# 5 6 2 2 2 10 12 9 | |
# | |
result = [] | |
serial_array = serial.split('') | |
num_array = [1, 2, 1, 2, 1, 2, 4, 1] | |
serial_array.zip(num_array) { |a, b| result << a.to_i * b } | |
# Step2 將所得值取出十位數及個位數 | |
# 十位數 個位數 | |
# 0 5 | |
# 0 6 | |
# 0 2 | |
# 0 2 | |
# 0 2 | |
# 1 0 | |
# 1 2 | |
# 0 9 | |
# | |
# 並將十位數與個位數全部結果值加總 | |
# | |
sum = 0 | |
result.each { |elm| | |
sum += elm.divmod(10).inject { |s, i| s + i } | |
} | |
# Step3 判斷結果 | |
# 第一種:加總值取10的餘數為0 | |
# 第二種:加總值取9的餘數等於9而且統編的第6碼為7 | |
return true if (sum % 10 == 0) or (sum % 9 == 9 and serial[5] == 7) | |
end | |
# 位數不足 | |
p company_serial_no_checker('5312539') # false | |
# 符合 | |
p company_serial_no_checker('53212539') # true | |
# 不符合 | |
p company_serial_no_checker('12222539') # nil, 在邏輯判斷的時候也會被當false |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
剛好做到統編驗證部分,謝謝見龍大分享
但這篇針對倒數第二位是7的統編驗證是錯的
第一個:我把sum % 9 == 9 改為 sum % 10 == 9 或 (sum + 1) % 10 == 0 (否則取九的餘數為九永遠不會成立)
第二個:serial[5] == 7 改為 serial[6] == '7' (第七位數的索引應為6,且右邊必須加上單引號表示字串,否則即使是7但型別卻仍然不符)
以上給後來需要的人一些修改參考