Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我使用 foo.to_yaml 保存了 Foo 类的对象。现在我向 Foo 类添加了一个实例变量,在初始化方法中将默认值设置为 0。现在,当我尝试从 yaml 文件加载对象时,实例变量设置为 nil。
如果 yaml 文件不包含该实例变量的任何值,是否可以通过某种方式将其设置为 0?
从磁盘加载对象后,是否有一些回调方法被调用?
您可以为该变量创建阅读器方法,例如
def your_instance_variable return "default" unless @your_instance_variable @your_instance_variable end
PS我前段时间正在做一些对象序列化任务,AFAIK Marshal.dump/load 快得多