Class: Numeric

Inherits:
Object show all
Defined in:
lib/extra/numeric.rb

Overview

See the math module, as methods from Math were added in Numeric dynamically.

Instance Method Summary collapse

Instance Method Details

#crop(range_or_min, max = nil) ⇒ Object

Credit to apeiros for this method.

Min/max method.

Example: -2.crop(0..1) # => 0

Returns: Numeric



72
73
74
75
76
77
78
79
80
81
# File 'lib/extra/numeric.rb', line 72

def crop(range_or_min, max=nil)
	range = max ? range_or_min..max : range_or_min
	if range.include?(self)
		self
	elsif self < range.first
		range.first
	else
		range.last
	end
end

#even?Boolean

Credit to manveru for this code. Checks whether a number is even.

Example:

5.even? #=> false

2.even? #=> true

Returns: True or false

Returns:

  • (Boolean)


15
16
17
# File 'lib/extra/numeric.rb', line 15

def even?
	self % 2 == 0
end

#format(comma = ',', decimal = '.') ⇒ Object

Add commas every 3 spots in a number.

Example: (4569810.12).format #=> 4,569,810.12

Returns: Commatized string



60
61
62
# File 'lib/extra/numeric.rb', line 60

def format(comma = ',', decimal = '.')
	to_s.reverse.scan(/(?:-?\d{1,3}(?:\.\d{1,3})?-?)/).map { |s| s.sub('.', decimal) }.join(comma).reverse
end

#negative?Boolean

Checks whether a number is a negative number. Example: -4.negative? #=> true

Returns: True or false

Returns:

  • (Boolean)


39
40
41
# File 'lib/extra/numeric.rb', line 39

def negative?
	self < 0
end

#odd?Boolean

Credit to manveru for this code. Checks whether a number is odd.

Example:

5.odd? #=> true

2.odd? #=> false

Returns: True or false

Returns:

  • (Boolean)


30
31
32
# File 'lib/extra/numeric.rb', line 30

def odd?
	self % 2 != 0
end

#positive?Boolean

Checks whether a number is positive. Here we will consider zero as being a positive number.

Example: 5.positive? #=> true

Returns: True or false

Returns:

  • (Boolean)


50
51
52
# File 'lib/extra/numeric.rb', line 50

def positive?
	self >= 0
end