Created
January 14, 2016 18:59
-
-
Save debreczeni/36fa2e0843e8f544a1f0 to your computer and use it in GitHub Desktop.
GIRO to IBAN converter in ruby
This file contains hidden or 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
class IBAN | |
def self.sanitize(account_number) | |
account_number.gsub(/\D*/, '') | |
end | |
def self.giro2iban(giro, country_code = 'HU') | |
giro = sanitize giro | |
country_code.upcase! | |
unless giro.size == 16 || giro.size == 24 | |
raise ArgumentError, "giro must be 16 or 24 digits long" | |
end | |
giro = "#{giro}00000000" if giro.size == 16 | |
base_str = "#{giro}#{country_code}00" | |
str = "" | |
base_str.chars.each do |char| | |
if char >= 'A' && char <= 'Z' | |
char = (char.ord - 55).to_s | |
end | |
str = str + char | |
end | |
base_str = str | |
str = "" | |
i = 0 | |
n = 9 | |
m = 0 | |
while i < base_str.size | |
x = (str + base_str[i, n]).to_i | |
m = x % 97 | |
str = m.to_s | |
i = i + n | |
n = 9 - str.length | |
end | |
check_digits = (98 - m).to_s | |
if check_digits.size == 1 | |
check_digits = '0' + check_digits | |
elsif check_digits.size != 2 | |
raise "Invalid number of check digits #{check_digits}" | |
end | |
country_code + check_digits + giro | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment