Class: Integer

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

Overview

MonkeyPatch Integers

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.square?(n) ⇒ Boolean

Integer.square? -> boolean

Returns whether the number is a square number

Integer.square?(1)          #=> true
Integer.square?(8)          #=> false
Integer.square?(36)         #=> true


74
75
76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/AnnieNumbers/IntegerMonkeyPatch.rb', line 74

def self.square?(n)
  n = n.to_i
  i = 1 # create starting number
  while true
    val = i*i  # create the square number of i
    if val == n
      return true
    end
    if val > n
      return false
    end
    i += 1
  end
end

.triangular?(n) ⇒ Boolean

Integer.triangular? -> boolean

Returns whether the number is triangular

Integer.triangular?(1)       #=> true
Integer.triangular?(2)       #=> false
Integer.triangular?(24)      #=> true


31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/AnnieNumbers/IntegerMonkeyPatch.rb', line 31

def self.triangular?(n)
  n = n.to_i
  i = 1 # create starting number
  while true
    val = (i*(i+1))/2  # create the triangular number to base of i
    if val == n
      return true
    end
    if val > n
      return false
    end
    i += 1
  end
end

Instance Method Details

#square?Boolean

Integer.square? -> boolean

Returns whether the number is a square number

1.square?          #=> true
8.square?          #=> false
36.square?         #=> true


53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/AnnieNumbers/IntegerMonkeyPatch.rb', line 53

def square?
  i = 1 # create starting number
  while true
    val = i*i  # create the square number of i
    if val == self
      return true
    end
    if val > self
      return false
    end
    i += 1
  end
end

#triangular?Boolean

#triangular? -> boolean

Returns whether the number is triangular

1.triangular?          #=> true
4.triangular?          #=> false
24.triangular?         #=> true


10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/AnnieNumbers/IntegerMonkeyPatch.rb', line 10

def triangular?
  i = 1 # create starting number
  while true
    val = (i*(i+1))/2  # create the triangular number to base of i
    if val == self
      return true
    end
    if val > self
      return false
    end
    i += 1
  end
end