Ruby dbm example

# $Id$
# example to store complex data in a database
# uses marshall from the standard library
require "sdbm"
db ="pleac14-8-database", 0666)
# convert the Objects into strings and back by using the Marshal module.
# Most normal objects can be converted out of the box,
# but not special things like procedure objects,
# IO instance variables, singleton objects
db["Tom Christiansen"] = Marshal.dump(["book author", ""])
db["Tom Boutell"] = Marshal.dump(["shareware author", ""])
name1 = "Tom Christiansen"
name2 = "Tom Boutell"
tom1 = Marshal.load(db[name1])
tom2 = Marshal.load(db[name2])
puts "Two Toming: #{tom1} #{tom2}"
if tom1[0] == tom2[0] && tom1[1] == tom2[1]
   puts "You're having runtime fun with one Tom made two."
   puts "No two Toms are ever alike"
# To change parts of an entry, get the whole entry, change the parts,
# and save the whole entry back
entry = Marshal.load(db["Tom Boutell"])
entry[0] = "Poet Programmer"
db["Tom Boutell"] = Marshal.dump(entry)

Back to Ruby

rubydbm.txt · Last modified: 2014/10/25 21:52 (external edit)
CC Attribution-Share Alike 3.0 Unported Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0