Skip to content

Instantly share code, notes, and snippets.

@D-system
Created October 29, 2019 13:16
Show Gist options
  • Save D-system/ba08cab0a3b4213b5b4964fb3d0093de to your computer and use it in GitHub Desktop.
Save D-system/ba08cab0a3b4213b5b4964fb3d0093de to your computer and use it in GitHub Desktop.
ISIN code validator in Ruby
class IsinCodeValidator
ISIN_FORMAT = '^[A-Z]{2}[A-Z0-9]{9}[0-9]$'.freeze
ISIN_REGEX = Regexp.new(ISIN_FORMAT).freeze
LETTER_TO_CODE_VALUE = 55 # Ascii code for 'A' == 65 && 'A' == 10 in isin calculation cod
def self.valid?(str)
return false if str.nil? || !str.match?(ISIN_REGEX)
proc_isin = str.split(//)
key = proc_isin.pop.to_i
proc_isin = proc_isin.map do |e|
e.match?(/[A-Z]/) ? (e.ord - LETTER_TO_CODE_VALUE).to_s.split(//) : e
end.flatten!.reverse!
proc_isin.each_index do |i|
proc_isin[i] = (proc_isin[i].to_i * 2).to_s.split(//) if (i % 2).zero?
end.flatten!
((key + proc_isin.map(&:to_i).inject(:+)) % 10).zero?
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment