Group attributes

Is it possible something like this:

group.set_attribute('katalog','zmienn',{:a1 =>1,:a2 =>2})

NO, the symbol keys cannot be saved into an attribute dictionary.
But you can use string keys in a hash and save it as a JSON string in an attribute dictionary.
(You cannot have symbol keys in a JSON (JavaScript Object Notation) string because JSON uses ‘:’ instead of ‘=>’.)

require 'json'

h1 = {'a1' =>1,'a2' =>2}
j1 = h1.to_json
#=> "{\"a1\":1,\"a2\":2}"

# Later ...
j2 = grp.get_attribute('katalog','zmienn')
h2 = JSON.parse(j2) # returns a Ruby hash object
#=> {"a1"=>1, "a2"=>2}
#=> Hash

So if you still want to use symbol keys in your hash, …

EDIT: (2018-01-12) @mamjankowski

I overlooked an option argument for JSON.parse() that WILL produce Ruby hashes using symbol keys.

ruby_hash = JSON.parse( json_str, symbolize_names => true )
# ... or for Ruby 2+ using named argument...
ruby_hash = JSON.parse( json_str, symbolize_names: true )


Custom methods to symbolize / stringify hash keys ... (click to expand) ...

(Collapsed on 2018-01-12 edit. No longer valid to discussion, but perhaps of geeky interest.)

… you will need (not really) to write your own methods to convert from JSON strings and hashes. OR just string keys to / from symbol keys, like:

def symbolize_keys(hash)
  h = {}
  hash.each {|k,v|
    h[k.to_sym]= v
  h # return the new hash with symbol keys

def stringify_keys(hash)
  h = {}
  hash.each {|k,v|
    h[k.to_s]= v
  h # return the new hash with string keys

Thanks, Dan.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.