Skip to content


Subversion checkout URL

You can clone with
Download ZIP
Tiny gem that may be useful for generating strings of digits that satisy the Luhn algorithm
branch: master

This branch is 8 commits behind rorymckinley:master

Fetching latest commit…

Cannot retrieve the latest commit at this time

Failed to load latest commit information.



A tiny (hopefully) gem that will automate some of the painful tasks of generating / validating strings of numbers based on the Luhn algorithm (e.g. credit card numbers, ID numbers).


To require:

require 'luhnacy'

Generic ValidationGeneration

To validate:


To generate a string of 10 digits that satisfies the Luhn algorithm:

valid_string = Luhnacy.generate(10)

To generate a string of 10 digits that does not satisfy Luhn algorithm:

invalid_string = Luhnacy.generate(10, :invalid => true)

To generate a string of 10 digits that satisfies Luhn and starts with predefined characters:

Luhnacy.generate(10, :prefix => '12345') #=> "1234597480"

Named Generators/Validators

There are named validators and generators for Visa, Mastercard and American Express credit cards. Note: Visa validation/generation only works for 16-digit credit card numbers.

Example usage (mastercard)

To validate a mastercard:


To generate a mastercard number that satisfies Luhn:

Luhnacy.mastercard #=> "5151199732615386"

To generate a master card number that does not satisfy Luhn:

Luhnacy.mastercard(:invalid => true)

Similar usage exists for Visa and American Express:

Planned changes

At some point it may make sense to store the patterns for the named generator in a seperate class/module or even in a YAML file. This will be driven by the need for additional named generators. If a YAML file is used, then the very next release may also include the ability to pass Luhnacy a custom YAML file for generating/validating strings.

Note on Patches/Pull Requests

  • Fork the project.

  • Make your feature addition or bug fix.

  • Add tests for it. This is important so I don't break it in a future version unintentionally.

  • Commit, do not mess with rakefile, version, or history. (if you want to have your own version, that is fine but bump version in a commit by itself I can ignore when I pull)

  • Send me a pull request. Bonus points for topic branches.



Copyright © 2010 Rory McKinley. See LICENSE for details.

Something went wrong with that request. Please try again.