Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<h2>A Variable Can Store a Key</h2> <p>Rather than trying to use indirect references or <a href="http://www.ruby-doc.org/core/Kernel.html#method-i-eval" rel="nofollow">Kernel#eval</a>, the Ruby way is to use a variable or expression to store or define the key you need. This isn't quite the same as your PHP code, but you can certainly use Ruby's native Hash methods to find the key for a given value.</p> <h2>Finding the Key You Want</h2> <blockquote> <p>I'm left wondering if there is a way to find the "parent" of an object so that I might modify it like I've done with branch["leaf"].</p> </blockquote> <p>Consider the nature of a hash: each key in a hash <em>must</em> be unique, although keys for nested hashes can be the same as a key in a parent or sibling hash. For example:</p> <pre><code># Keys for nested hashes can be the same. tree = { branch1: { leaf: 'green' }, branch2: { leaf: 'red' }, } #=&gt; {:branch1=&gt;{:leaf=&gt;"green"}, :branch2=&gt;{:leaf=&gt;"red"}} # Duplicate keys; last one "wins." tree = { branch: { leaf: 'green' }, branch: { leaf: 'red' }, } #=&gt; {:branch=&gt;{:leaf=&gt;"red"} </code></pre> <p>On the bright side, that means that any given level of your hash will have exactly <em>one</em> key that matches what you want. There are any number of ways to find it. One example is using <a href="http://www.ruby-doc.org/core-2.0/Hash.html#method-i-rassoc" rel="nofollow">Hash#rassoc</a> to return the key you want:</p> <pre><code>tree.rassoc( {leaf: 'red'} ).first #=&gt; :branch2 </code></pre> <p>Other methods like <a href="http://www.ruby-doc.org/core-2.0/Hash.html#method-i-select" rel="nofollow">#select</a>, <a href="http://www.ruby-doc.org/core-2.0/Hash.html#method-i-each_pair" rel="nofollow">#each_pair</a>, and so forth may also be useful, depending on your needs and the semantics of what you're trying to express.</p> <h2>Using the Key Name</h2> <p>Once you have the key, you can use that key to modify the associated value for that key. For example:</p> <pre><code>tree = { branch1: { leaf: 'green' }, branch2: { leaf: 'red' }, } key = tree.rassoc( {leaf: 'red'} ).first tree[key] = { leaf: 'blue' } tree #=&gt; {:branch1=&gt;{:leaf=&gt;"green"}, :branch2=&gt;{:leaf=&gt;"blue"}} </code></pre>
 

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