Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You could be lazy, and wrap it in a <code>lambda</code>:</p> <pre><code>my_hash = YAML.load_file('yml') my_lamb = lambda { |key| my_hash[key.to_s] } my_lamb[:a] == my_hash['a'] #=&gt; true </code></pre> <p>But this would only work for reading from the hash - not writing.</p> <p>To do that, you could use <code>Hash#merge</code></p> <pre><code>my_hash = Hash.new { |h,k| h[k] = h[k.to_s] }.merge(YAML.load_file('yml')) </code></pre> <p>The init block will convert the keys one time on demand, though if you update the value for the string version of the key after accessing the symbol version, the symbol version won't be updated.</p> <pre><code>irb&gt; x = { 'a' =&gt; 1, 'b' =&gt; 2 } #=&gt; {"a"=&gt;1, "b"=&gt;2} irb&gt; y = Hash.new { |h,k| h[k] = h[k.to_s] }.merge(x) #=&gt; {"a"=&gt;1, "b"=&gt;2} irb&gt; y[:a] # the key :a doesn't exist for y, so the init block is called #=&gt; 1 irb&gt; y #=&gt; {"a"=&gt;1, :a=&gt;1, "b"=&gt;2} irb&gt; y[:a] # the key :a now exists for y, so the init block is isn't called #=&gt; 1 irb&gt; y['a'] = 3 #=&gt; 3 irb&gt; y #=&gt; {"a"=&gt;3, :a=&gt;1, "b"=&gt;2} </code></pre> <p>You could also have the init block not update the hash, which would protect you from that kind of error, but you'd still be vulnerable to the opposite - updating the symbol version wouldn't update the string version:</p> <pre><code>irb&gt; q = { 'c' =&gt; 4, 'd' =&gt; 5 } #=&gt; {"c"=&gt;4, "d"=&gt;5} irb&gt; r = Hash.new { |h,k| h[k.to_s] }.merge(q) #=&gt; {"c"=&gt;4, "d"=&gt;5} irb&gt; r[:c] # init block is called #=&gt; 4 irb&gt; r #=&gt; {"c"=&gt;4, "d"=&gt;5} irb&gt; r[:c] # init block is called again, since this key still isn't in r #=&gt; 4 irb&gt; r[:c] = 7 #=&gt; 7 irb&gt; r #=&gt; {:c=&gt;7, "c"=&gt;4, "d"=&gt;5} </code></pre> <p>So the thing to be careful of with these is switching between the two key forms. Stick with one.</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.
    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