Skip to content

Instantly share code, notes, and snippets.

@radcliff
Last active August 29, 2015 14:25
Show Gist options
  • Save radcliff/210f2986039630c6c8c7 to your computer and use it in GitHub Desktop.
Save radcliff/210f2986039630c6c8c7 to your computer and use it in GitHub Desktop.
Design a spreadsheet engine in Ruby
require 'spreadsheet'
require 'minitest/autorun'
class TestSpreadsheet < MiniTest::Test
def setup
@sheet = Spreadsheet.new([2,2], "Sheet")
end
def test_for_iniatialize
assert_equal(2, @sheet.rows)
assert_equal(2, @sheet.cols)
assert_equal("Sheet", @sheet.title)
end
def test_for_cell
foo = @sheet.cell([0,0],"Foo")
assert_equal("Foo", foo) # method return value
assert_equal("Foo", @sheet.cell([0,0])) # accessing cell
assert_nil(@sheet.cell([0,1]))
assert_raises(IndexError) do
@sheet.cell([3,0])
end
assert_raises(IndexError) do
@sheet.cell([0,3])
end
end
end
class Spreadsheet
attr_reader :rows, :cols, :data
attr_accessor :title
def initialize(dimensions = [], title = nil)
rows = dimensions[0]
cols = dimensions[1]
@data = Array.new(rows) { Array.new(cols) }
@title = title
end
def rows
@data.size
end
def cols
@data[0].size
end
def cell(position, value = nil)
row = position[0]
col = position[1]
raise IndexError if row > @data.size or col > @data[row].size
if value
@data[row][col] = value # set
else
value = @data[row][col] # get
end
return value
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment