Search code examples
ruby-on-railsjsonrubyputs

How to print an object element inside an array in ruby


I have to print in shell the description of my error, and I can't access to the element inside an object inside an array and I'm still learning Ruby.

I've tried

rescue => e
  puts e.fields[description]
...

and doesn't work.

{
  "code": "123",
  "message": "Invalid data.",
  "fields": [
    {
      "name": "test",
      "description": "testing"
    }
  ]
}

---> I want to print only testing

Thank you

so much for your help :)


Solution

  • How about

    h = {:code=>"123", :message=>"Invalid data.", :fields=>[{:name=>"test", :description=>"testing"}]}

    then

    h.dig(:fields, 0, :description)