【问题标题】:Issue with saving and then retrieving hash table in Rails and memcached在 Rails 和 memcached 中保存然后检索哈希表的问题
【发布时间】:2014-03-22 17:41:46
【问题描述】:

我在我的 Windows 机器上使用 Ruby on Rails 和 memcached。我创建了一个哈希,然后使用 Rails 将其存储在 memcached 中。在我保存之前,该变量的类类型是散列。当我从缓存中读取时,变量类最终成为数组......有什么帮助避免这种情况吗?我不能使用 Rails 将哈希存储在 memcached 中吗?为什么检索时类型会发生变化?谢谢。

示例代码...

my_hash = Hash.new
my_hash["foo"] = 23
my_hash["bar"] = 33
#my_hash.class.to_s => hash
Rails.cache.write("key1", my_hash)

retrieved_hash = Rails.cache.read("key1")
#retrieved_hash.class.to_s => array

【问题讨论】:

  • 你能贴出对你返回的对象执行 .inspect 的结果吗?

标签: ruby-on-rails arrays hash memcached hashtable


【解决方案1】:

类的类型没有变化

1.9.3p194 :014 > my_hash = Hash.new
 => {} 
1.9.3p194 :015 > my_hash["foo"] = 23
 => 23 
1.9.3p194 :016 > my_hash["bar"] = 33
 => 33 
1.9.3p194 :017 > my_hash.class
 => Hash 
1.9.3p194 :018 > Rails.cache.write("key1", my_hash)
 => true 
1.9.3p194 :019 > retrieved_hash = Rails.cache.read("key1")
 => {"foo"=>23, "bar"=>33} 
1.9.3p194 :020 > retrieved_hash.class
 => Hash 

在这两种情况下,类都与哈希相同。

【讨论】:

  • 你是对的。在我的代码中,在另一个地方,我使用了相同的哈希键,并且我正在编写覆盖我之前编写的数组的数组。感谢您确认这应该有效。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-09-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-30
  • 2012-08-30
相关资源
最近更新 更多