From: Robert Klemme Date: 2012-04-05T00:23:51+09:00 Subject: Re: using hash as database? Secure databases with ruby? ruby rocks wrote in post #1054850: > database = {} > database.store(user + "_contact", contact) > > > and then when it is time to get the users contact list, I will search > the hash with a regular expression looking for the current users chunk > of _contact entries, and then return each of them to get the full list > of contacts. That is not using the Hash properly. If you have a key value store (which is another way to look at a Hash) you want to do lookups based on key and not iterate the whole thing. > But I will have multiple sorts of information stored in one > hash, that I will also write to the disk and load from disk into a hash > when the program is running (or maybe when it is time to use it only?). The "multiple sorts of information" bit is a tad too vague to properly comment. Can you explain what are the keys (beyond "user" which you did mention already) and what sort of information do you want to store? For a simplistic database I would define a class and write down the public interface, e.g. UserInfo = Struct.new :name, :age, :contacts do def add_contact(contact) (self.contacts ||= [] ) << contact end end class DB def add_user(user_info) end def get_user_by_name(user_name) end ... end Then you know what access paths you need for the various bits of information and can decide how many Hashes you have inside a single DB instance. Persistence can be done via Marshal which is pretty fast. irb(main):003:0> x=Hash[100_000.times.map{|i| [i.to_s, "*"*100]}]; x.size => 100000 irb(main):004:0> Benchmark.measure { File.open("x","wb") {|io|Marshal.dump(x,io)} } => 0.500000 0.015000 0.515000 ( 0.515622) irb(main):005:0> Benchmark.measure { File.open("x","rb") {|io|Marshal.load(io)} } => 0.437000 0.016000 0.453000 ( 0.453122) If you need it to be faster and / or save space on disk you could write custom serialization which only writes the raw info but not the indexes (Hashes) and creates those when reading. Kind regards robert -- Posted via http://www.ruby-forum.com/.