Class: Numeric
Overview
See the math module, as methods from Math were added in Numeric dynamically.
Instance Method Summary collapse
-
#crop(range_or_min, max = nil) ⇒ Object
Credit to apeiros for this method.
-
#format(comma = ',', decimal = '.') ⇒ Object
Add commas every 3 spots in a number.
-
#negative? ⇒ Boolean
Checks whether a number is a negative number.
-
#positive? ⇒ Boolean
Checks whether a number is positive.
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
43 44 45 46 47 48 49 50 51 52 |
# File 'lib/extra_lib/core_ext/numeric.rb', line 43 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 |
#format(comma = ',', decimal = '.') ⇒ Object
Add commas every 3 spots in a number.
Example: (4569810.12).format #=> 4,569,810.12
Returns: Commatized string
31 32 33 |
# File 'lib/extra_lib/core_ext/numeric.rb', line 31 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
10 11 12 |
# File 'lib/extra_lib/core_ext/numeric.rb', line 10 def negative? self < 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
21 22 23 |
# File 'lib/extra_lib/core_ext/numeric.rb', line 21 def positive? self >= 0 end |