Skip to content

Instantly share code, notes, and snippets.

@kugaevsky
Last active December 31, 2015 19:19
Show Gist options
  • Save kugaevsky/8033004 to your computer and use it in GitHub Desktop.
Save kugaevsky/8033004 to your computer and use it in GitHub Desktop.
Russian taxpayer id validator
class TaxpayerID
FACTORS = [ 3, 7, 2, 4, 10, 3, 5, 9, 4, 6, 8, 0 ]
def initialize value
@digits = value.to_s.chars.map(&:to_i)
raise ArgumentError, 'unexpected argument length (must be 10 or 12 chars)' unless @digits.length == 10 || @digits.length == 12
@result = (@digits.length == 10 ? check_ten : check_twelve)
end
def valid?
@result
end
def to_s
@digits.join
end
def to_i
to_s.to_i
end
private
def check_ten
calc_check_number(FACTORS.last(10)) == @digits.last
end
def check_twelve
[ FACTORS.last(11), FACTORS ].map{ |f| calc_check_number(f) } == @digits.last(2)
end
def calc_check_number(factors)
control_sum = factors.each_with_index.map{ |k, i| k*@digits[i] }.reduce(:+)
(control_sum % 11) > 9 ? 0 : (control_sum % 11)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment