class Integer
Constants
- FACTORIAL
Memoization container: integer => factorial(integer)
Public Instance Methods
factorial → anInteger
click to toggle source
Calculate the factorial of int. To use the memoized version: Integer.send(:alias_method, :factorial, :factorial_memoized)
# File lib/nuggets/integer/factorial.rb 37 def factorial 38 (1..self).inject { |f, i| f * i } 39 end
factorial_memoized → anInteger
click to toggle source
Calculate the factorial of int with the help of memoization (Which gives a considerable speedup for repeated calculations – at the cost of memory).
WARNING: Don't try to calculate the factorial this way for “large” integers! This might well bring your system down to its knees… ;-)
# File lib/nuggets/integer/factorial.rb 49 def factorial_memoized 50 FACTORIAL[self] ||= (1..self).inject { |f, i| FACTORIAL[i] ||= f * i } 51 end
to_binary_s → aString
click to toggle source
to_binary_s(length) → aString
Returns int as binary number string; optionally zero-padded to length
.
# File lib/nuggets/integer/to_binary_s.rb 34 def to_binary_s(length = nil) 35 "%0#{length}d" % to_s(2) 36 end
to_dotted_decimal → aString
click to toggle source
Converts int to dotted-decimal notation.
# File lib/nuggets/dotted_decimal.rb 35 def to_dotted_decimal 36 to_binary_s(32).unpack('a8' * 4).map { |s| s.to_i(2) }.join('.') 37 end