Search code examples
jsonrubyruby-hash

How to change hash return format for Ruby


I have the following hash:

{"description":"Hello","id":"H"}`

If I type the hash in the console, I get:

{:description=>"Hello", :id=>"H"}

I would like it to return the same form mentioned first, using "description" and "id".

Is there a way to change the format in which my hash is returned?


Solution

  • You have an Hash with Symbol keys:

    h = {"description": "Hello", "id": "H"}
    

    Consider this:

    ({"description": "Hello", "id": "H"}) == ({"description"=> "Hello", "id"=> "H"})
    #=> false
    
    ({"description": "Hello", "id": "H"}) == ({description: "Hello", id: "H"})
    #=> true
    

    Ruby just removes " when printing:

    p ({"description":"Hello","id":"H"})
    #=> {:description=>"Hello", :id=>"H"}
    

    If you want to convert keys to String, you could use pure Ruby Hash#transform_keys (or the bang version transform_keys!):

    h.transform_keys &:to_s
    #=> {"description"=>"Hello", "id"=>"H"}
    

    If a json is what you are looking for, do:

    require 'json'
    
    puts h.to_json
    #=> {"description":"Hello","id":"H"}
    

    Consider also that:

    h.to_json.class #=> String
    h.class #=> Hash