EAN number with correct checksum (boilerplate function)

Functions of Mockaroo is an awesome tool, but it is a little unclear / subtle how to return values from the function and how to do things.

SO as a proof of concept, and a tutorial for others, here is a simple function to generate correct checksum for EAN13 codes. (checksums are generally missing from Mockaroo…). A suggestion could be to include the “barcode1dtools” library.

In any case, here goes. Code found here: Class: Barcode1DTools::EAN13 — Documentation for barcode1dtools (1.0.2.0)

# Input is expected to be 12 digits
# No check for this.
# save the original content which is stored in "this" 
ean = this

# Set a value
mult = 3

# Modify original "this" value
this = this.split('').inject(0) { |a,c| mult = 4 - mult ; a + c.to_i * mult }

# Calculate the modula10 value, and store to "checksum"
checksum = (10 - (this % 10)) % 10

# Output resulting line. 
# LAST string to print returns the value.
# Using a formatter line, see Ruby Docs.
"#{ean}#{checksum}"