How do I convert hash keys to method names?

前端 未结 5 585
暖寄归人
暖寄归人 2020-12-02 14:37

This is my hash:

tempData = {\"a\" => 100, \"here\" => 200, \"c\" => \"hello\"}

I need to access the hash keys as a method like:

5条回答
  •  自闭症患者
    2020-12-02 14:58

    There is another way to do this.

    JSON.parse(tempData.to_json, object_class: OpenStruct)

    that will give object #

    In this way nested hash also will be converted to OpenStruct Object

    tempData = {a: { b: { c: 3}}, foo: 200, msg: 'test msg'}
    obj = JSON.parse(tempData.to_json, object_class: OpenStruct)
    

    Now we are able to call

    obj.a.b.c # 3
    obj.foo # 200
    obj.msg # 'test msg'
    

    Hope this will help someone.

提交回复
热议问题