Store a hash as an value in an attribute dictionary
-
Is this possible:
result={"1"=>"one", "2"=>"two"}
Sketchup.active_model.set_attribute 'test','test1',resultI tried it and when i do
puts (Sketchup.active_model.get_attribute 'test','test1') it returns nilIs this because it is a hash it can not be shown or because the hash is not stored?
If it is not possible: is there another solution?
Off course i could create a seperate dictionary for each key in the hash but that will give me a lot of dictionaries.thx
-
Pout,
I don't think you're allowed to store arrays, hashes, etc. inside attributes.
You could convert your object into a string with .inspect and then eval it back into an object. Here's a project with utilities for that kind of thing. (Disclaimer: I've not used it personally.)
http://rubyforge.org/projects/ron/
Cheers,
-
Pout, you can store anything you want in an attribute dictionary, but that doesn't mean you can get it back out how you want it!
The term for what you are trying to do is "marshal". You can look it up in the Ruby book, or google it. YAML (Yet Another Marshaling Language) is a great example that comes with the whole ruby install, as it saves vars and values in text format we humans can read.
If you know the keys you want to save, just use your var names as the attribute keys, and the values as the attribute values. Simple simple.
-
@pout said:
Off course i could create a seperate dictionary for each key in the hash but that will give me a lot of dictionaries.
Is your hash a simple hash like you show in your example? If so, you can create the dictionary very easily.
# Create a Hash h = {"a"=>0, "m"=>100, "y"=>300, "n"=>100, "d"=>200} # Write each key=value pair to a dictionary h.map{|k, v| Sketchup.active_model.set_attribute("Dictionary", k, v)} # Retrieve the dictionary dic = Sketchup.active_model.attribute_dictionaries["Dictionary"] # output as an array dic.to_a [["a", 0], ["d", 200], ["m", 100], ["n", 100], ["y", 300]]
I count one dictionary per hash.
-
thanks all for the fast answers.
The dictionary setup should be like this:
dict, number1, hash1
dict, number2, hash2
dict, number3, hash3Jim, if i am not mistaking you put the hash key in place of number 1, number 2 and number 3 and the hash value each time as the value.
I need one more level:
The hash itself should be the value of number 1, number 2 and number 3
So with your example it should be
dict, number1, {"a"=>0, "m"=>100, "y"=>300, "n"=>100, "d"=>200}Todd, when i store the hash it does not give me an error. But when i return it it is always nil
If it was stored wouldn't it return me an error telling that it can not be displayed insteda of returning nil?On the other hand i now have used an array to do it. Off course this is not as intelligent. So if possible i would prefer using a hash.
Maybe important: the dictionary is a model dictionary, not an entity dictionary -
Advertisement