1

I'm writing a simple function in a ruby script to get the ID attribute from some JSON data.

def getObjectTypeId()
    objects = post(@server.oS.getAllTypeObjectCounts())
    myObject = objects.find_all{|xObjectCountInfo| xObjectCountInfo['ObjectInfo']['ObjectTypeID'] == 'myObjectTypeID'}
    puts myObject
    @objectTypeId = myObject['ObjectInfo']['ID']
end

The error is happening on the final line of the function. As you can see, I'm printing myObject to the console to verify that it's a hash and not an array (which is the most common issue I've seen that causes this error). Here's a snippet of the output:

{"_class"=>"XObjectCountInfo", "ObjectInfo"=>{"_class"=>"XObjectInfo", "ID"=>"10102", "ObjectTypeID"=>"myObjectTypeID"}}

What could be causing me to get the "can't convert String to Integer" type error?

1
  • 2
    Please use snake_case instead of camelCase when naming functions an variables in Ruby. This is the standard. Commented Dec 2, 2013 at 20:07

2 Answers 2

3

Enumerable#find_all gives an array when used with block. Your myObject is an array of size 1, I am quite sure. You used puts method to print it, so you are seeing the only one element hash of the array. Use p myObject, you will get to see that the object myObject is an one element array. Your modified last statement @objectTypeId = myObject['ObjectInfo']['ID'], will be @objectTypeId = myObject.map{|h| h['ObjectInfo']['ID'] }

I used Enumerable#map as, #find_all returns an array of collection. This time you have only one element in the array,but any time you can have more than one element. In this case #map would be a good choice I think.

Sign up to request clarification or add additional context in comments.

Comments

0

If the exception is really raised on the last line of the method you provided, either myObject or my myObject['ObjectInfo'] is an array not a hash.

I'm suspecting the myObject as it is returned by find_all

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.