1
votes

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?

2
Please use snake_case instead of camelCase when naming functions an variables in Ruby. This is the standard. - Dan Grahn
Good to know, thanks! - elemjay19

2 Answers

3
votes

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.

0
votes

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