Class: Integer

Inherits:
Object show all
Defined in:
lib/epitools/core_ext/numbers.rb,
lib/epitools/core_ext/truthiness.rb

Constant Summary collapse

BASE62_DIGITS =

Cached constants for base62 encoding

['0'..'9', 'A'..'Z', 'a'..'z'].map(&:to_a).flatten
BASE62_BASE =
BASE62_DIGITS.size

Instance Method Summary collapse

Instance Method Details

#blank?Boolean

‘true’ if the integer is 0



61
# File 'lib/epitools/core_ext/truthiness.rb', line 61

def blank?; self == 0; end

#factObject Also known as: factorial

Factorial



317
318
319
320
321
322
323
324
325
# File 'lib/epitools/core_ext/numbers.rb', line 317

def fact
  if self < 0
    -(1..-self).reduce(:*)
  elsif self == 0
    1
  else
    (1..self).reduce(:*)
  end
end

#factorsObject

Returns the all the prime factors of a number.



309
310
311
312
# File 'lib/epitools/core_ext/numbers.rb', line 309

def factors
  Prime # autoload the prime module
  prime_division.map { |n,count| [n]*count }.flatten 
end

#fibObject Also known as: fibonacci

Fibonacci (recursive style)



331
332
333
# File 'lib/epitools/core_ext/numbers.rb', line 331

def fib
  self < 2 ? self : (self-1).fib + (self-2).fib
end

#integer?Boolean



63
# File 'lib/epitools/core_ext/truthiness.rb', line 63

def integer?; true; end

#prime?Boolean

Am I a prime number?



302
303
304
# File 'lib/epitools/core_ext/numbers.rb', line 302

def prime?
  Prime.prime? self
end

#to_base62Object

Convert a number to a string representation (in “base62” encoding).

Base62 encoding represents the number using the characters: 0..9, A..Z, a..z

It’s the same scheme that url shorteners and YouTube uses for their ID strings. (eg: www.youtube.com/watch?v=dQw4w9WgXcQ)



282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
# File 'lib/epitools/core_ext/numbers.rb', line 282

def to_base62
  result = []
  remainder = self
  max_power = ( Math.log(self) / Math.log(BASE62_BASE) ).floor
  
  max_power.downto(0) do |power|
    divisor = BASE62_BASE**power
    #p [:div, divisor, :rem, remainder]      
    digit, remainder = remainder.divmod(divisor)
    result << digit
  end
  
  result << remainder if remainder > 0
  
  result.map{|digit| BASE62_DIGITS[digit]}.join ''
end

#to_bitsObject Also known as: bits

Convert the number to an array of bits (least significant digit first, or little-endian).



262
263
264
265
# File 'lib/epitools/core_ext/numbers.rb', line 262

def to_bits
  # TODO: Why does thos go into an infinite loop in 1.8.7?
  ("%b" % self).chars.to_a.reverse.map(&:to_i)
end

#to_hexObject

Convert the number into a hexadecimal string representation. (Identical to to_s(16), except that numbers < 16 will have a 0 in front of them.)



255
256
257
# File 'lib/epitools/core_ext/numbers.rb', line 255

def to_hex
  "%0.2x" % self
end