Skip to content

Instantly share code, notes, and snippets.

@onnimonni
Last active January 5, 2018 14:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save onnimonni/02514d297ff0366f1fa6a78876e616e7 to your computer and use it in GitHub Desktop.
Save onnimonni/02514d297ff0366f1fa6a78876e616e7 to your computer and use it in GitHub Desktop.
Finnish bank reference calculator in ruby
# Array#sum is needed for nice code outside rails projects
require 'active_support'
require 'active_support/core_ext'
# Module for creating valid Finnish bank references
module FinnishBankRefence
# Generates reference from a input or a random number
def self.generate( base = rand(10**3..(10**19-1)) )
if base < 10**3 or base >= 10**19
raise ArgumentError, "Valid reference has 3..19 digits, #{base} has #{base.to_s.length}"
end
"#{base}#{checksum(base)}"
end
# Calculates Finnish bank reference checksum.
# Checksum is calculated from a sum where all digits are weighted with coefficient
# The coefficient is from 7,3,1 sequence starting from the smallest digit
# Checksum is the reverse of modulo10 which can be done with x = -y % 10
# For example: "617435 4"
# 6 1 7 4 3 5 4
# 1 3 7 1 3 7
# 6 3 49 4 9 35 = 106 → 4
#
# Source http://tarkistusmerkit.teppovuori.fi/tarkmerk.htm#viitenumero
def self.checksum(base)
weighted_sum = base.to_s.reverse.each_char.with_index.map { |digit,index| digit.to_i * [7,3,1].at(index%3) }.sum
-weighted_sum % 10
end
end
20.times { puts FinnishBankRefence::generate }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment