构造嵌套的OpenStruct对象

时间:2017-11-24 22:37:06

标签: ruby openstruct

我必须模仿Google API响应并创建一个可由.遍历的2级深度数据结构,如下所示:

=> user.names.first_name
  

鲍勃

有没有比这更聪明/更好的方法:

 user = OpenStruct.new(names: OpenStruct.new(first_name: 'Bob'))

1 个答案:

答案 0 :(得分:2)

这种方法粗鲁但有效,

require 'ostruct'
require 'json'
# Data in hash
data = {"names" => {"first_name" => "Bob"}}
result = JSON.parse(data.to_json, object_class: OpenStruct)

另一种方法是向Hash类本身添加方法,

class Hash
  def to_openstruct
    JSON.parse to_json, object_class: OpenStruct
  end
end

使用上述方法,您可以将哈希转换为openstruct

data = {"names" => {"first_name" => "Bob"}}
data.to_openstruct