Hello everybody,
I've written a class that should create a simple database (like dbdbd of David
Alan Black, but I didn't quite understand it so I tried to write one on my own
to learn a bit more about ruby).
Here's a little script that uses this database:
# test.rb
require "UDB"
array = %w{Name Age Size Lines}
database = UDB.new(array)
hash = { "Name" => "Urban", "Age" => 19, "Size" => 1.73, "Lines" => 35 }
database.test
database.write(hash)
database.test
database.typeout
And here are the error is get:
$ ruby test.rb
key: Age value: 1
key: Size value: 2
key: Lines value: 3
key: Name value: 0
./UDB.rb:31:in `fetch': key not found (IndexError)
from ./UDB.rb:31:in `write'
from ./UDB.rb:29:in `each'
from ./UDB.rb:29:in `write'
from test.rb:10
Well,...
I think that the problem is somewhere, where I use the hashes @row and @index
but I don't know what I did wrong.
Thanks for your help
Urban
--
class UDB
def initialize(columnames)
@columnames = columnames
# The Database of this object
@database = Array.new
count = 0
# Put all the columnames into the database
@columnames.each do |name|
@column = Array.new
@column[0] = name
@database[count] = @column
count += 1
end
@index = {}
count = 0
# Register all the columns in a hash
@database.each do |name|
@index[name] = count
count += 1
end
end
def test
@index.each { |key,value| print "key: ", key ," value: ", value, "\n" }
end
# Write new entry into the database
def write(row)
@row = row
@row.each do |key,value|
# Get Number of the column
columno = @index.fetch(key)
columno = columno.to_i
# Make new entry
@database[columno].push(value)
end
end
# Write the database to stdout
def typeout
# Get number of rows
0.upto(@database[0].length - 1) do |row|
0.upto(@index.length - 1) do |column|
print " #{@database[column][row]} "
end
print "\n"
end
end
end