Collecting hashes into OpenStruct creates “table” entry

前端 未结 6 937
滥情空心
滥情空心 2021-02-04 05:46

Why this (evaluated in Rails console)

[{:a => :b}].collect {|x| OpenStruct.new(x)}.to_json

adds a \"table\" record in there?



        
6条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-04 06:10

    I found the other responses to be a tad confusing having landed here to just figure out how to turn my OpenStruct into a Hash or JSON. To clarify, you can just call marshal_dump on your OpenStruct.

    $ OpenStruct.new(hello: :world).to_json
    => "{\"table\":{\"hello\":\"world\"}}"
    
    $ OpenStruct.new(hello: :world).marshal_dump
    => {:hello=>:world}
    
    $ OpenStruct.new(hello: :world).marshal_dump.to_json
    => "{\"hello\":\"world\"}"
    

    I personally would be hesitant to monkey-patch OpenStruct unless you're doing it on a subclass, as it may have unintended consequences.

提交回复
热议问题