Class: IMW::Counter
- Inherits:
-
Object
- Object
- IMW::Counter
- Defined in:
- lib/imw/utils/misc.rb
Overview
A simple counter. The value
and add
methods read and increment the counter’s value.
counter = IMW::Counter.new
counter.value #=> 0
counter.add 1
counter.value #=> 1
The next!
method acts as like C’s value++
, incrementing value
after it is referenced.
counter = IMW::Counter.new
counter.value #=> 0
counter.next! #=> 0
counter.value #=> 1
Counters can also be reset
counter.reset!
counter.value #=> 0
Instance Attribute Summary collapse
-
#increment ⇒ Object
Returns the value of attribute increment.
-
#starting_value ⇒ Object
Returns the value of attribute starting_value.
-
#value ⇒ Object
Returns the value of attribute value.
Instance Method Summary collapse
-
#add(amount = nil) ⇒ Object
(also: #add!)
Add
amount
(defaults to the value of@increment
). -
#initialize(starting_value = 0, increment = 1) ⇒ Counter
constructor
Return a new Counter.
-
#next! ⇒ Object
Increment the counter by
@increment
but return its value before being incremented. -
#reset!(value = nil) ⇒ Object
Reset the counter to
value
(defaults to the value of@starting_value
).
Constructor Details
#initialize(starting_value = 0, increment = 1) ⇒ Counter
Return a new Counter. The first argument is the starting value (defaults to 0) and the second is the increment (defaults to 1).
29 30 31 32 33 |
# File 'lib/imw/utils/misc.rb', line 29 def initialize starting_value=0,increment=1 @starting_value = starting_value @value = starting_value @increment = increment end |
Instance Attribute Details
#increment ⇒ Object
Returns the value of attribute increment.
25 26 27 |
# File 'lib/imw/utils/misc.rb', line 25 def increment @increment end |
#starting_value ⇒ Object
Returns the value of attribute starting_value.
25 26 27 |
# File 'lib/imw/utils/misc.rb', line 25 def starting_value @starting_value end |
#value ⇒ Object
Returns the value of attribute value.
25 26 27 |
# File 'lib/imw/utils/misc.rb', line 25 def value @value end |
Instance Method Details
#add(amount = nil) ⇒ Object Also known as: add!
Add amount
(defaults to the value of @increment
).
36 37 38 |
# File 'lib/imw/utils/misc.rb', line 36 def add amount=nil @value += amount || @increment end |
#next! ⇒ Object
Increment the counter by @increment
but return its value before being incremented.
43 44 45 46 47 |
# File 'lib/imw/utils/misc.rb', line 43 def next! old_value = @value @value += @increment old_value end |
#reset!(value = nil) ⇒ Object
Reset the counter to value
(defaults to the value of @starting_value
).
51 52 53 |
# File 'lib/imw/utils/misc.rb', line 51 def reset! value=nil @value = value || @starting_value end |