Class: SecretNumber::Application

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

Instance Method Summary collapse

Constructor Details

#initialize(argv) ⇒ Application

Returns a new instance of Application


8
9
10
11
12
13
14
15
16
17
# File 'lib/secret_number.rb', line 8

def initialize(argv)
  raise NoArgumentFoundError, 'You must supply an integer as an argument' if argv[0] == nil
  # Only match digits
  raise IntegerNotFoundError, 'Sorry, the argument you pass must be an integer' unless argv[0] =~ /\d+/
  # Raise if decimal
  raise IntegerNotFoundError, 'Sorry, the argument you pass must be an integer' unless argv[0].to_i.to_s == argv[0]
  # Raise if negative
  raise IntegerNotFoundError, 'Sorry, the argument you pass must be a positive integer' if argv[0].to_i < 0
  @number = argv[0].to_i
end

Instance Method Details

#is_prime(test_number = @number) ⇒ Object


29
30
31
32
33
34
35
36
37
# File 'lib/secret_number.rb', line 29

def is_prime(test_number = @number)
  return false if test_number.abs < 2
  for number in 2..(test_number - 1)
    if (test_number % number) == 0
      return false
    end
  end
  return true
end

#is_secret_additive(test_number = @number) ⇒ Object


39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/secret_number.rb', line 39

def is_secret_additive(test_number = @number)
  prime_array = []
  counter = 0
  while counter < test_number
    prime_array << counter if is_prime(counter)
    counter += 1
  end

  prime_array.each do |x|
    prime_array.each do |y|
      return false if secret(x + y) != secret(x) + secret(y)
    end
  end
  return true
end

#runObject


19
20
21
22
23
24
25
26
27
# File 'lib/secret_number.rb', line 19

def run
  if is_secret_additive
    puts "The secret function for the integer #{@number} is additive"
    exit 0
  else
    puts "The secret function for the integer #{@number} is not additive"
    exit 1
  end
end

#secret(integer) ⇒ Object


55
56
57
# File 'lib/secret_number.rb', line 55

def secret(integer)
  integer
end