def test_full_expression
sheet = Sheet.new
sheet.put("A1", "=7*(2+3)*((((2+1))))")
assert_equal("105", sheet.get("A1"))
end
def test_simple_formula_error
sheet = Sheet.new
sheet.put("A1", "=7*")
assert_equal("#Error", sheet.get("A1"))
end
--
thanks,
-pate
-------------------------
# ----- 8< -------
class Sheet
NUMERIC = /^\s+(\d+)\s+$/
FORMULA = /^=(.+)$/
def initialize
@storage = {}
end
def get( cell )
normalize( get_literal( cell ))
end
def get_literal( cell )
@storage[cell] ||= ''
end
def put( cell, data )
@storage[cell] = data
end
private
def normalize( data )
case data
when NUMERIC then $1
when FORMULA then formula_eval( $1 )
else data
end
end
def formula_eval( formula )
eval( formula ).to_s
rescue SyntaxError
'#Error'
end
end
# ----- 8< -------
The only change I had to make for this set is the rescue block on the
formula_eval method. eval took care of the other two new tests fine.
Jacob Fugal
class Sheet
NUMERIC = /^\s*(\d+)\s*$/
FORMULA = /^=(.*)$/
def initialize
@cells = Hash.new("")
end
def put(cell, val="")
@cells[cell] = val
end
def get(cell)
case @cells[cell]
when NUMERIC then $1
when FORMULA
begin
(eval $1).to_s
rescue SyntaxError
'#Error'
end
else @cells[cell]
end
end
def get_literal(cell)
@cells[cell]
end
end
--
Bill Guindon (aka aGorilla)
I guess it also depends on who this library is for. If it's intended
as a backend for end-user applications, eval() has to go. If it's
intended as a development library, having it may be a big win. It's
all point of view I guess.
Here's my code:
#!/usr/local/bin/ruby -w
# SimpleSpread.rb
#
# Created by James Edward Gray II on 2005-11-05.
# Copyright 2005 Gray Productions. All rights reserved.
require "forwardable"
class Sheet
extend Forwardable
def initialize
@cells = Hash.new { |cells, cell| cells[cell] = "" }
end
def get( cell )
case @cells[cell]
when /^\s*(\d+)\s*$/
$1
when /^=(.*)$/
eval($1).to_s
else
@cells[cell]
end
rescue Exception
"#Error"
end
def_delegator :@cells, :[], :get_literal
def_delegator :@cells, :[]=, :put
end
__END__
James Edward Gray II
My sentiments exactly.
Jacob Fugal
[1] Apologies for the content-free post, but I have no elaboration to add... :)