Class: Integer

Inherits:
Object show all
Defined in:
lib/nano/integer/fact.rb,
lib/nano/numeric/succ.rb,
lib/nano/float/round_at.rb,
lib/nano/float/round_to.rb,
lib/nano/integer/odd%3F.rb,
lib/nano/integer/even%3F.rb,
lib/nano/integer/factorial.rb,
lib/nano/integer/times_map.rb,
lib/nano/integer/multiple%3F.rb,
lib/nano/integer/times_collect.rb

Instance Method Summary collapse

Instance Method Details

#even?Boolean

Is an integer even?

2.even?  #=> true
3.even?  #=> false

Returns:

  • (Boolean)


10
11
12
# File 'lib/nano/integer/even%3F.rb', line 10

def even?
  self % 2 == 0
end

#factObject

Common alias for #factorial.

2.fact  #=> 2
3.fact  #=> 6
4.fact  #=> 24


11
# File 'lib/nano/integer/fact.rb', line 11

alias_method( :fact, :factorial )

#factorialObject

Calculate the factorial of an integer.

2.factorial  #=> 2
3.factorial  #=> 6
3.factorial  #=> 24


10
11
12
13
14
15
# File 'lib/nano/integer/factorial.rb', line 10

def factorial
  return 1 if self == 0
  #self == 0 ? 1 : ( self * (self-1).factorial )
  f = (1..self.abs).inject { |state, item| state * item }
  return self < 0 ? -f : f
end

#multiple?(number) ⇒ Boolean

Is is a multiple of a given number?

7.multiple?(2)  #=> false
8.multiple?(2)  #=> true

Returns:

  • (Boolean)


8
9
10
# File 'lib/nano/integer/multiple%3F.rb', line 8

def multiple?(number)
  self % number == 0
end

#odd?Boolean

Is an integer odd?

2.odd?  #=> false
3.odd?  #=> true

Returns:

  • (Boolean)


10
11
12
# File 'lib/nano/integer/odd%3F.rb', line 10

def odd?
  self % 2 == 1
end

#round_at(*args) ⇒ Object

To properly support Float’s rounding methods, Integer must also be augmented.



27
28
29
# File 'lib/nano/float/round_at.rb', line 27

def round_at(*args)
  self.to_f.round_at(*args)
end

#round_to(*args) ⇒ Object

To properly support Float’s rounding methods, Integer must also be augmented.



28
29
30
# File 'lib/nano/float/round_to.rb', line 28

def round_to(*args)
  self.to_f.round_to(*args)
end

#times_collect(&yld) ⇒ Object

Like #times but returns a collection of the yield results.

a = 3.times_collect { |i| "#{i+1}" }
a => [ "1", "2", "3" ]


9
10
11
12
# File 'lib/nano/integer/times_collect.rb', line 9

def times_collect(&yld)
  a = []; self.times{ |i| a << yld.call(i) }
  a
end

#times_mapObject



4
# File 'lib/nano/integer/times_map.rb', line 4

alias_method :times_map, :times_collect