Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>If you happen to be in Rails then you'll have <a href="http://api.rubyonrails.org/classes/Hash.html#method-i-symbolize_keys" rel="noreferrer"><code>symbolize_keys</code></a>:</p> <blockquote> <p>Return a new hash with all keys converted to symbols, as long as they respond to <code>to_sym</code>.</p> </blockquote> <p>and <code>symbolize_keys!</code> which does the same but operates in-place. So, if you're in Rails, you could:</p> <pre><code>hash.symbolize_keys! </code></pre> <p>If you want to recursively symbolize inner hashes then I think you'd have to do it yourself but with something like this:</p> <pre><code>def symbolize_keys_deep!(h) h.keys.each do |k| ks = k.to_sym h[ks] = h.delete k symbolize_keys_deep! h[ks] if h[ks].kind_of? Hash end end </code></pre> <p>You might want to play with the <code>kind_of? Hash</code> to match your specific circumstances; using <code>respond_to? :keys</code> might make more sense. And if you want to allow for keys that don't understand <code>to_sym</code>, then:</p> <pre><code>def symbolize_keys_deep!(h) h.keys.each do |k| ks = k.respond_to?(:to_sym) ? k.to_sym : k h[ks] = h.delete k # Preserve order even when k == ks symbolize_keys_deep! h[ks] if h[ks].kind_of? Hash end end </code></pre> <p>Note that <code>h[ks] = h.delete k</code> doesn't change the content of the Hash when <code>k == ks</code> but it will preserve the order when you're using Ruby 1.9+. You could also use the <code>[(key.to_sym rescue key) || key]</code> approach that Rails uses in their <code>symbolize_keys!</code> but I think that's an abuse of the exception handling system.</p> <p>The second <code>symbolize_keys_deep!</code> turns this:</p> <pre><code>{ 'a' =&gt; 'b', 'c' =&gt; { 'd' =&gt; { 'e' =&gt; 'f' }, 'g' =&gt; 'h' }, ['i'] =&gt; 'j' } </code></pre> <p>into this:</p> <pre><code>{ :a =&gt; 'b', :c =&gt; { :d =&gt; { :e =&gt; 'f' }, :g =&gt; 'h' }, ['i'] =&gt; 'j' } </code></pre> <p>You could monkey patch either version of <code>symbolize_keys_deep!</code> into Hash if you really wanted to but I generally stay away from monkey patching unless I have very good reasons to do it.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload