开发者

How do I make a persistent hash in Ruby?

I would like a persistent hash; an object that act as a hash, but that can persist between program runs.

Ideally, it would only 开发者_如何学JAVAload in memory the value that are accessed.


Since persistent key/value storage is kind of everyones requirement, as it happens there are a large number of solutions.

YAML is probably the easiest way to persist Ruby objects.

JSON works as well but doesn't directly handle symbols.

MySQL and other SQL databases such as sqlite3 also solve this problem, of course. Usually, access is encapsulated within the ActiveRecord ORM library.

The Ruby core has a Marshaling library.


Using sdbm

require 'sdbm'

SDBM.open("/mypath/myfile.dbm") do |myMap|
    [...]

    myMap[key] = avalue

    [...]

    myvar = myMap[anotherKey]

    [...]
end

create to files : myfile.dbm.dir and myfile.dbm.pag


I would consider using redis-rb, which has a hash datatype. This would not only persist your hash across program runs, but across multiple machines. It's super fast, in memory, and you can have it up and running in < 5 minutes.

in IRB (assuming you've installed and are running redis-server and have installed redis-rb:

require "redis"
redis = Redis.new

The important operations are:

redis.hset(key, field, value)

and

redis.hget(key,field)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜