2

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

demir
  • 4,591
  • 2
  • 22
  • 30
AFAF
  • 569
  • 2
  • 16
  • 40
  • 2
    try this: `e[:fields].first[:description]` – demir Oct 29 '19 at 11:31
  • You show `e` as if it is a hash, is that the case? Or are `code`, `message` and `fields` methods of `e`? (because that seems more appropriate for an error-object --but it could well be the case. – nathanvda Oct 29 '19 at 12:25

6 Answers6

4

How about

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

then

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

Bhagawat
  • 468
  • 4
  • 12
1
e["fields"].each do |field|
 puts field["description"]
end 
SBN
  • 123
  • 7
0

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

0

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
0

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

nathanvda
  • 49,707
  • 13
  • 117
  • 139
0

If you want the comma separated descriptions

descriptions = e["fields"].map{|f| f["description"]}.join(',')
puts descriptions
zawhtut
  • 8,335
  • 5
  • 52
  • 76