gpt4 book ai didi

ruby - 将 marshal_load 与 OpenStruct 结合使用

转载 作者:数据小太阳 更新时间:2023-10-29 07:45:23 24 4
gpt4 key购买 nike

如何使用 OpenStruct 的 marshal_load 实用程序?它似乎没有按预期工作。

文档给出 this example , 但它似乎不起作用。

require 'ostruct'

event = OpenStruct.new
hash = { 'time' => Time.now, 'title' => 'Birthday Party' }
event.marshal_load(hash)
event.title # => nil

如果不是这种方式,我如何将散列加载到 OpenStruct 中(不使用构造函数)?

对于上下文:我正在从 YAML 文件中加载哈希并将其加载到 OpenStruct 子类的现有实例中。

最佳答案

尝试使用基于符号的哈希。这对我有用。

#works.rb

hash = { :time => Time.now, :title => 'Birthday Party' }
event.marshal_load(hash)

关于ruby - 将 marshal_load 与 OpenStruct 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14331371/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com