Skip to content

Instantly share code, notes, and snippets.

@ShaneDelmore
Last active December 20, 2015 02:59
Show Gist options
  • Select an option

  • Save ShaneDelmore/6059868 to your computer and use it in GitHub Desktop.

Select an option

Save ShaneDelmore/6059868 to your computer and use it in GitHub Desktop.
Playing around with enumerable.
#Make a grid_location class to make it easier to address grid coordinates.
class Cell
attr_reader :column, :row, :letter
def initialize(row, column, letter='')
@column = column
@row = row
@letter = letter
end
def move(direction)
@column += direction.column
@row += direction.row
return self
end
end
class WordFinderGrid
include Enumerable
attr_reader :grid, :height, :width
def initialize(array)
@height = array.length
@width = array[0].length
@grid = Array.new(@height) do |row|
Array.new(@width)
end
# @grid = array.map { |line| line.chars }
array.each_with_index do |row, row_index|
row.chars.each_with_index do |letter, col_index|
@grid[row_index][col_index] = Cell.new(row_index, col_index, letter )
end
end
end
# def each()
# 0.upto(height - 1) do |row_index|
# 0.upto(width - 1) do |col_index|
# # p self[row_index, col_index]
# self[row_index, col_index](&block)
# end
# end
# end
def each
if block_given?
@grid.each do |row|
row.each do |cell|
yield (cell)
end
end
else
to_enum
end
# @grid.each do |row|
# row.each(&block)
# end
end
def [](row, column)
@grid[row][column] if @grid[row]
end
end
grid = WordFinderGrid.new(["ABC"])
# p grid
# p grid[0,0]
# grid.each { |cell| p cell.class }
grid.grid.each do |cell|
p cell.letter
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment