cnpj-dv for Ruby
Gem Version Downloads Count Ruby Version Test Status Last Update Date Project License
π Full support for the new alphanumeric CNPJ format.
A Ruby utility to calculate check digits on CNPJ (Brazilian Business Tax ID).
Ruby Support
| Ruby 3.2 | Ruby 3.3 | Ruby 3.4 |
|---|---|---|
| Passing β | Passing β | Passing β |
Features
- β Alphanumeric CNPJ: Full support for the new alphanumeric CNPJ format (introduced in 2026)
- β
Flexible input: Accepts
StringorArrayof strings - β Format agnostic: Strips non-alphanumeric characters from string input and uppercases letters
- β Auto-expansion: Multi-character strings in arrays are joined and parsed like a single string
- β
Input validation: Rejects ineligible CNPJs (all-zero base ID
00000000, all-zero branch0000, or 12 numeric-only repeated digits) - β Lazy evaluation: Check digits are calculated only when accessed (via methods)
- β Caching: Calculated values are cached for subsequent access
- β
Minimal dependencies: Only
[lacus-utils](https://rubygems.org/gems/lacus-utils) - β
Error handling: Specific types for type, length, and invalid CNPJ scenarios (
TypeErrorvsStandardErrorsemantics)
Installation
Install the gem directly:
gem install cnpj-dv
Or add it to your Gemfile and run bundle install:
gem 'cnpj-dv'
Require
require 'cnpj-dv'
Quick Start
require 'cnpj-dv'
check_digits = CnpjDV::CnpjCheckDigits.new('914157320007')
check_digits.first # => '9'
check_digits.second # => '3'
check_digits.both # => '93'
check_digits.cnpj # => '91415732000793'
With alphanumeric CNPJ (new format):
require 'cnpj-dv'
check_digits = CnpjDV::CnpjCheckDigits.new('MGKGMJ9X0001')
check_digits.first # => '6'
check_digits.second # => '8'
check_digits.both # => '68'
check_digits.cnpj # => 'MGKGMJ9X000168'
Usage
The main resource of this package is the class CnpjDV::CnpjCheckDigits. Through an instance, you access CNPJ check-digit information:
initialize:CnpjDV::CnpjCheckDigits.new(cnpj_input)βcnpj_inputmust be aStringor anArrayof strings. After sanitization, the value must have 12β14 alphanumeric characters (formatting stripped from strings; letters uppercased). Only the first 12 characters are used as the base; if you pass 13 or 14 characters (e.g. a full CNPJ including prior check digits), characters 13β14 are ignored and the digits are recalculated. There are no options, keyword arguments, or configuration objects β the constructor takes only the CNPJ input.first: First check digit (13th character of the full CNPJ). Lazy, cached.second: Second check digit (14th character of the full CNPJ). Lazy, cached.both: Both check digits concatenated as a string.cnpj: The complete CNPJ as a string of 14 characters (12 base characters + 2 check digits).
Input formats
The CnpjCheckDigits class accepts multiple input formats:
String input: raw digits and/or letters, or formatted CNPJ (e.g. 91.415.732/0007-93, MG.KGM.J9X/0001-68). Non-alphanumeric characters are removed; lowercase letters are uppercased.
Array of strings: each element must be a string; values are concatenated and then parsed like a single string (e.g. ['9','1','4',β¦], ['9141','5732','0007'], ['MG','KGM','J9X','0001']). Non-string elements are not allowed.
require 'cnpj-dv'
# String β plain, formatted, or with existing check digits (only first 12 chars used)
CnpjDV::CnpjCheckDigits.new('914157320007')
CnpjDV::CnpjCheckDigits.new('91.415.732/0007')
CnpjDV::CnpjCheckDigits.new('91415732000793')
# Array of strings β single- or multi-character elements
CnpjDV::CnpjCheckDigits.new(%w[9 1 4 1 5 7 3 2 0 0 0 7])
CnpjDV::CnpjCheckDigits.new(%w[9141 5732 0007])
CnpjDV::CnpjCheckDigits.new(%w[MG KGM J9X 0001])
Errors & exceptions handling
This package uses TypeError vs StandardError semantics: type errors indicate incorrect API use (e.g. wrong type); exceptions indicate invalid or ineligible data (e.g. invalid length or business rules). You can rescue specific classes or use the base classes.
CnpjDV::CnpjCheckDigitsTypeErrorβ base class for type errors; extends RubyβsTypeErrorCnpjDV::CnpjCheckDigitsInputTypeErrorβ input is notStringorArrayof strings (or array contains a non-string element)CnpjDV::CnpjCheckDigitsExceptionβ base class for data/flow exceptions; extendsStandardErrorCnpjDV::CnpjCheckDigitsInputLengthExceptionβ sanitized length is not 12β14CnpjDV::CnpjCheckDigitsInputInvalidExceptionβ base ID00000000, branch ID0000, or 12 identical numeric digits (repeated-digit pattern)
require 'cnpj-dv'
# Input type (e.g. integer not allowed)
begin
CnpjDV::CnpjCheckDigits.new(12_345_678_000_100)
rescue CnpjDV::CnpjCheckDigitsInputTypeError => e
puts e.
# => CNPJ input must be of type string or string[]. Got integer number.
end
# Length (must be 12β14 alphanumeric characters after sanitization)
begin
CnpjDV::CnpjCheckDigits.new('12345678901')
rescue CnpjDV::CnpjCheckDigitsInputLengthException => e
puts e.
# => CNPJ input "12345678901" does not contain 12 to 14 characters. Got 11.
end
# Invalid (e.g. all-zero base or branch, or repeated numeric digits)
begin
CnpjDV::CnpjCheckDigits.new('000000000001')
rescue CnpjDV::CnpjCheckDigitsInputInvalidException => e
puts e.
# => CNPJ input "000000000001" is invalid. Base ID "00000000" is not eligible.
end
# Any data exception from the package
begin
CnpjDV::CnpjCheckDigits.new('000000000001')
rescue CnpjDV::CnpjCheckDigitsException => e
puts e.
end
Notable attributes on raised errors:
CnpjCheckDigitsInputTypeError:actual_input,actual_type,expected_typeCnpjCheckDigitsInputLengthException:actual_input,evaluated_input,min_expected_length,max_expected_lengthCnpjCheckDigitsInputInvalidException:actual_input,reason
Other available resources
After require 'cnpj-dv':
CnpjDV::CNPJ_MIN_LENGTH:12CnpjDV::CNPJ_MAX_LENGTH:14- Exceptions: see above
Calculation algorithm
The package computes check digits with the official Brazilian modulo-11 rules extended to alphanumeric characters:
- Character value: each character contributes
ord(character) β 48(so0β9stay 0β9; letters use their ASCII offset from0). - Weights: from right to left, multiply by weights that cycle 2, 3, 4, 5, 6, 7, 8, 9, then repeat from 2.
- First check digit (13th position): apply steps 1β2 to the first 12 base characters; let
r = sum % 11. The digit is0ifr < 2, otherwise11 β r. - Second check digit (14th position): apply steps 1β2 to the first 12 characters plus the first check digit; same formula for
r.
Contribution & Support
We welcome contributions! Please see our Contributing Guidelines for details. If you find this project helpful, please consider:
- β Starring the repository
- π€ Contributing to the codebase
- π‘ Suggesting new features
- π Reporting bugs
License
This project is licensed under the MIT License β see the LICENSE file for details.
Changelog
See CHANGELOG for a list of changes and version history.
Made with β€οΈ by Lacus Solutions