convert hash to object

后端 未结 6 731
小蘑菇
小蘑菇 2021-02-07 03:06

I am trying to convert hash and nested hashes to objects.

so far first hash object is converted successfully by this code:

class Hashit
  def initialize(         


        
6条回答
  •  星月不相逢
    2021-02-07 03:43

    Another way is to use JSON and OpenStruct, which are standard ruby libs:

    irb:
    > require 'JSON'
    => true
    
    > r = JSON.parse({a: { b: { c: 1 }}}.to_json, object_class: OpenStruct)
    => #>>
    
    > r.a.b.c
    => 1
    

提交回复
热议问题