How to print an object element inside an array in ruby

Viewed 1434

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 :)

6 Answers

How about

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

then

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

e["fields"].each do |field|
 puts field["description"]
end 

You can do this - e[:fields][0][:description]

In your response fields, the key is containing an array object.

If you want to print the specific value then you need to use an index like this e["fileds"][0] then this will print "testing".

If you want to print all the description then you should do like this:

e["fileds"].each do |field|
   puts field["description"]
end

If e is a Hash, as one could deduce from the way you show the contents of e, you could write

e["fields"][0]["description"]

As usual in Rails there are many ways to achieve the same, and sometimes not.

You could also write e[:fields][0][:description] but only if the Hash has indifferent access, which means you can use strings and symbols interchangeably (that is by default, if you create a hash yourself, not the case).

So to explain the line in more detail: e["fields"] returns an array (of hashes), take the first element: e["fields"][0] or e["fields"].first and then get the value for the key description in the hash.

However, if you created a class that inherited from StandardError which is what is usually thrown on error, you would most likely have to write something like:

 e.fields 

which returns the array of fields. To find the first element, we write, again e.fields[0] or e.fields.first, and then it depends if the array contains hashes, or objects with a method description, so it could either be

e.fields[0].description 

or

e.fields[0][:description] 

(I prefer to write the symbol key, but please remember if your Hash has strings as keys and is not a HashWithIndifferentAccess you will have to use the string "description")

If you want the comma separated descriptions

descriptions = e["fields"].map{|f| f["description"]}.join(',')
puts descriptions
Related