简体   繁体   English

如何在Ruby中进行持久性哈希处理?

[英]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 load 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. YAML可能是持久保存Ruby对象的最简单方法。

JSON works as well but doesn't directly handle symbols. JSON也可以,但不能直接处理符号。

MySQL and other SQL databases such as sqlite3 also solve this problem, of course. MySQL和其他SQL数据库(例如sqlite3)当然也可以解决此问题。 Usually, access is encapsulated within the ActiveRecord ORM library . 通常,访问权限封装在ActiveRecord ORM库中

The Ruby core has a Marshaling library . Ruby核心具有Marshaling库

Using sdbm 使用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 创建到文件:myfile.dbm.dir和myfile.dbm.pag

I would consider using redis-rb , which has a hash datatype. 我会考虑使用具有哈希数据类型的redis-rb 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. 它的内存速度非常快,您可以在不到5分钟的时间内启动并运行它。

in IRB (assuming you've installed and are running redis-server and have installed redis-rb: 在IRB中(假设您已安装并正在运行redis-server并已安装redis-rb:

require "redis"
redis = Redis.new

The important operations are: 重要的操作有:

redis.hset(key, field, value)

and

redis.hget(key,field)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM