Class: Array2D
- Inherits:
-
Object
- Object
- Array2D
- Defined in:
- lib/2DArray.rb
Instance Method Summary collapse
-
#[](x, y) ⇒ Object
Returns the object at
x
,y
. -
#[]=(x, y, new) ⇒ Object
Set the object at
x
,y
tonew
. -
#each ⇒ Object
Iterate through each element, while passing the object, its
x
andy
position to the block. -
#include?(thing) ⇒ Boolean
Returns if
thing
is an element. -
#initialize(rows = 0, cols = 0, default = nil) ⇒ Array2D
constructor
A new instance of Array2D.
-
#method_missing(m, *args, &block) ⇒ Object
Redefined Object#method_missing as to forward the undefined method to @stuff, an array.
- #size ⇒ Object
-
#width ⇒ Object
Returns the number of rows.
Constructor Details
#initialize(rows = 0, cols = 0, default = nil) ⇒ Array2D
Returns a new instance of Array2D.
2 3 4 |
# File 'lib/2DArray.rb', line 2 def initialize(rows=0, cols=0, default=nil) @stuff = Array.new(rows) {Array.new(cols, default)} end |
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(m, *args, &block) ⇒ Object
Redefined Object#method_missing as to forward the undefined method to @stuff, an array. You can even pass blocks, too, otherwise this would be pretty useless…
25 26 27 28 29 30 31 |
# File 'lib/2DArray.rb', line 25 def method_missing(m, *args, &block) if @stuff.respond_to?(m) @stuff.flatten(1).send(m, *args) {|*b_args| block.call(*b_args)} else super(m, *args) end end |
Instance Method Details
#[](x, y) ⇒ Object
Returns the object at x
, y
.
43 44 45 46 47 48 49 |
# File 'lib/2DArray.rb', line 43 def [](x, y) # Return +nil+ if there is nothing at the given position. if @stuff[x] == nil return nil end @stuff[x][y] end |
#[]=(x, y, new) ⇒ Object
Set the object at x
, y
to new
.
34 35 36 37 38 39 40 |
# File 'lib/2DArray.rb', line 34 def []=(x, y, new) # Initialize the array for +x+ if it hasn't already been. if @stuff[x] == nil @stuff[x] = [] end @stuff[x][y] = new end |
#each ⇒ Object
Iterate through each element, while passing the object, its x
and y
position to the block.
7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
# File 'lib/2DArray.rb', line 7 def each x = 0 y = 0 size.times do |s| yield(self[x, y], x, y) # Restart at +width - 1+ because the array starts at +0, 0+ not +1, 1+. if x == width - 1 x = 0 y += 1 else x += 1 end end end |
#include?(thing) ⇒ Boolean
Returns if thing
is an element.
52 53 54 |
# File 'lib/2DArray.rb', line 52 def include?(thing) @stuff.flatten(1).include?(thing) end |
#size ⇒ Object
56 57 58 |
# File 'lib/2DArray.rb', line 56 def size @stuff.flatten(1).size end |
#width ⇒ Object
Returns the number of rows.
61 62 63 |
# File 'lib/2DArray.rb', line 61 def width @stuff.size end |