Class: Numeric

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

Overview

Numeric extensions

Instance Method Summary collapse

Instance Method Details

#floor_precision(precision) ⇒ Object

Returns self, truncated to a given precision.

Examples:

x = 0.12345
x.floor_precision(0) => 0.0
x.floor_precision(1) => 0.1
x.floor_precision(2) => 0.12
x.floor_precision(3) => 0.123

Returns:

  • self, truncated to a given precision



53
54
55
56
# File 'lib/sixarm_ruby_ramp/numeric.rb', line 53

def floor_precision(precision)
  return self if is_a?(Float) && nan?
  (self * (10 ** precision)).truncate.fdiv(10 ** precision)
end

#if(flag) ⇒ Object

Returns 0 if the given flag is any of: nil, false, 0, [], {}.

Examples:

3.if(true) => 3
3.if(false) => 0

Returns:

  • 0 if the given flag is any of: nil, false, 0, [], {}



14
15
16
# File 'lib/sixarm_ruby_ramp/numeric.rb', line 14

def if(flag)
  if [nil,false,0,[],{}].include?(flag) then 0 else self end
end

#percent(ndigits = 0) ⇒ Object

Returns self as a percent, i.e. * 100 then call round.

Examples:

x = 0.12345
x.percent => 12
x.percent(1) => 12.3
x.percent(2) => 12.34
x.percent(-1) => 10

Returns:

  • self as a percent, i.e. * 100 then call round.



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

def percent(ndigits=0)
  (self * 100).round(ndigits)
end

#unless(flag) ⇒ Object

Returns self if flag is nil, false, 0, [], {}; otherwise return 0.

Examples:

3.unless(true) => 0
3.unless(false) => 3

Returns:

  • self if flag is nil, false, 0, [], {}; otherwise return 0.



25
26
27
# File 'lib/sixarm_ruby_ramp/numeric.rb', line 25

def unless(flag)
  if [nil,false,0,[],{}].include?(flag) then self else 0 end
end