Associative Arrays (Hashes) and the Attribute Library

Is it okay to store associative arrays within the attribute libraries? I thought I saw somewhere that this is not possible.

I’m already storing text, numbers, points and multi dimensional arrays.

I can test it on this end but I just wanted to check with others if this will cause any known issues or stability problems etc…

When I try to store a basic hash I only get nil.

Here is the test hash I’m creating and trying to store:

testhash = Hash.new
testhash[2] = [192.0,5.5]
testhash[5] = [48.0,5.5]
testhash[7] = [144.0,3.5]

groupi.set_attribute 'TRUSS', 'BPHASH', testhash

Yet I can store this multi-dimensional mess of an array:

[ [ 2, [192.0, 5.5]], [ 5, [48.0, 7.5]], [ 7,[144.0,3.5]]]

testarray = Array.new
testarray << [2,[192.0,5.5]]
testarray << [5,[48.0,7.5]]
testarray << [7,[144.0,3.5]]

instancei.set_attribute 'TRUSS', 'BPHASH', testarray

testarray2 = instancei.get_attribute 'TRUSS', 'BPHASH'
puts "#{testarray2}, #{testarray2[1][1][1]}"

It is strange to me that we cannot store hashes in the attribute library, why is that?

You might try using json. I’m pretty sure it can handle Hashes and there should be no issue storing them in attribute dictionaries because json is pure strings.

2 Likes

Yep, I second the use of JSON.

groupi.set_attribute( 'TRUSS', 'BPHASH', testhash.to_json )

… and sometime later:

restored_hash = JSON.parse(groupi.get_attribute( 'TRUSS', 'BPHASH' ))
1 Like

If the possibility of nested hashes exists now or in the future, then json is probably best.

If not, Hash#to_a and Array#to_h may be helpful.