Class: TurkishId

Inherits:
Object
  • Object
show all
Defined in:
lib/turkish_id.rb,
lib/turkish_id/version.rb

Constant Summary collapse

VERSION =
"0.2.0"

Instance Method Summary collapse

Constructor Details

#initialize(id_number) ⇒ TurkishId

Returns a new instance of TurkishId.



5
6
7
8
9
10
11
12
# File 'lib/turkish_id.rb', line 5

def initialize(id_number)
  begin
    # Convert string into array of integers
    @id_number = id_number.split('').map { |s| Integer(s) }
  rescue
    @id_number = ''  # Suppress error & return false (eventually)
  end
end

Instance Method Details

#is_valid?Boolean

Returns:

  • (Boolean)


14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/turkish_id.rb', line 14

def is_valid?
  id = @id_number  # +1 brevity point

  # Early elimination, bad length or first digit
  return false if id.length != 11 || id.first == 0

  # Calculate the sums of odd and even digits
  odds = id.values_at(0, 2, 4, 6, 8).reduce(:+)
  evens = id.values_at(1, 3, 5, 7).reduce(:+)

  # Check if the tenth digit matches the algorithm
  return false if id[9] != ((odds * 7) - evens) % 10

  # Check if the eleventh digit matches the algorithm
  return false if id[10] != id[0..9].reduce(:+) % 10

  return true  # All conditions met
end