Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy is a string key for a hash frozen?
    primarykey
    data
    text
    <p>According to the <a href="http://www.ruby-doc.org/core-1.9.3/Hash.html#method-i-store">specification</a>, strings that are used as a key to a hash are duplicated and frozen. Other mutable objects do not seem to have such special consideration. For example, with an array key, the following is possible.</p> <pre><code>a = [0] h = {a =&gt; :a} h.keys.first[0] = 1 h # =&gt; {[1] =&gt; :a} h[[1]] # =&gt; nil h.rehash h[[1]] # =&gt; :a </code></pre> <p>On the other hand, a similar thing cannot be done with a string key.</p> <pre><code>s = "a" h = {s =&gt; :s} h.keys.first.upcase! # =&gt; RuntimeError: can't modify frozen String </code></pre> <p>Why is string designed to be different from other mutable objects when it comes to a hash key? Is there any use case where this specification becomes useful? What other consequences does this specification have?</p> <p><hr> I actually have a use case where absence of such special specification about strings may be useful. That is, I read with the <code>yaml</code> gem a manually written YAML file that describes a hash. the keys may be strings, and I would like to allow case insensitivity in the original YAML file. When I read a file, I might get a hash like this:</p> <pre><code>h = {"foo" =&gt; :foo, "Bar" =&gt; :bar, "BAZ" =&gt; :baz} </code></pre> <p>And I want to normalize the keys to lower case to get this:</p> <pre><code>h = {"foo" =&gt; :foo, "bar" =&gt; :bar, "baz" =&gt; :baz} </code></pre> <p>by doing something like this:</p> <pre><code>h.keys.each(&amp;:downcase!) </code></pre> <p>but that returns an error for the reason explained above.</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.
 

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