# Module: Sjekksum::UPC

Extended by:
Shared, UPC
Included in:
UPC
Defined in:
lib/sjekksum/upc.rb

## Overview

Module for calculation and validation of UPC (Universal Product Code) checksums

It's like Luhn but multiplies by 3 instead of 2. Also it must allow validation of numbers with leading zeros.

## Instance Method Details

### #convert(number) ⇒ Integer, StringAlso known as: transform

Transforms a number by appending the UPC checksum digit

It will preserve type (Integer/String) and therefore leading zeros.

Examples:

``Sjekksum::UPC.convert("03600024145") #=> "036000241457"``

Parameters:

• number (Integer, String)

number without a checksum

Returns:

• (Integer, String)

final number including the checksum

 ``` 62 63 64 65``` ```# File 'lib/sjekksum/upc.rb', line 62 def convert number raise_on_type_mismatch number typed_conversion number end```

### #of(number) ⇒ IntegerAlso known as: checksum

Calculates UPC checksum

Examples:

``Sjekksum::UPC.of("03600024145") #=> 7``

Parameters:

• number (Integer, String)

number for which the checksum should be calculated

Returns:

• (Integer)

calculated checksum

 ``` 23 24 25 26 27 28 29 30 31 32``` ```# File 'lib/sjekksum/upc.rb', line 23 def of number raise_on_type_mismatch number digits = convert_number_to_digits(number) sum = digits.map.with_index do |digit, idx| idx.even? ? (digit * 3) : digit end.reduce(&:+) (10 - sum % 10) % 10 end```

### #valid?(number) ⇒ BooleanAlso known as: is_valid?

UPC validation of provided number

Examples:

``Sjekksum::UPC.valid?("036000241457") #=> true``

Parameters:

• number (Integer, String)

number with included checksum

Returns:

• (Boolean)
 ``` 44 45 46 47 48``` ```# File 'lib/sjekksum/upc.rb', line 44 def valid? number raise_on_type_mismatch number num, check = split_number(number) self.of(num) == check end```