Class: Luhnacy

Inherits:
Object
  • Object
show all
Defined in:
lib/luhnacy.rb

Class Method Summary collapse

Class Method Details

.generate(string_size, options = {}) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/luhnacy.rb', line 6

def self.generate(string_size, options={})
  output = ''
  (string_size-1).times do |n|
    output += rand(10).to_s
  end
  output += '0'

  if options[:invalid]
    case calc_modulus(output)
    when 0
      output = output[0...-1] + (rand(8) + 1).to_s
    when [1..8]
      output = output[0...-1] + ((10 - calc_modulus(output))/2).to_s
    when 9
      output = output[0...-1] + (rand(7) + 2).to_s
    end
  else
    unless calc_modulus(output) == 0
      output = output[0...-1] + (10 - calc_modulus(output)).to_s
    end
  end

  output
end

.valid?(candidate) ⇒ Boolean

Returns:

  • (Boolean)


2
3
4
# File 'lib/luhnacy.rb', line 2

def self.valid?(candidate)
  calc_modulus(candidate) == 0
end