Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <h2>This is good but not great; see below for a much-simplified method.</h2> <pre><code>def hash_to_eval_chain(hsh) make_eval_chain(hsh).join "." end private def make_eval_chain(obj) if obj.is_a? Hash raise "Hash cannot contain multiple key-value pairs unless they are nested" if obj.size &gt; 1 return make_eval_chain(obj.to_a.flatten) elsif obj.is_a? Array return [ obj.first, *make_eval_chain(obj.last) ] if obj.last.is_a? Hash return obj if [String, Symbol, Array].include? obj.class raise "Only strings, symbols, and hashes are allowed as values in the hash." else raise "Expected Hash, received #{obj.class}" end end # Usage: # irb&gt; hash_to_eval_chain { :one =&gt; { :two=&gt; { :three =&gt; { :four=&gt; :five } } } } # =&gt; "one.two.three.four.five" </code></pre> <p>I couldn't find an elegant way to roll it all into one function, so I hope two will suffice.</p> <p>Basically I realized that <code>{:one =&gt; {:two =&gt; :three}}.to_a.flatten</code> returns <code>[:one, {:two =&gt; :three}]</code> and said A-ha!, this is classic car/cdr-style recursion.</p> <h2>BETTER METHOD:</h2> <p>You know what, I was making that WAY harder than necessary. This is better (inspired by Facets' <a href="http://facets.rubyforge.org/apidoc/api/core/classes/Hash.html#M000197" rel="nofollow noreferrer">Hash#recursively</a> method):</p> <pre><code>def hash_to_eval_chain(hsh) make_eval_chain(hsh).flatten.join "." end private def make_eval_chain(obj) if obj.is_a? Hash return obj.map {|key, val| [key, *make_eval_chain(val)] } if obj.is_a?(Hash) &amp;&amp; obj.size &lt;= 1 raise "Hash cannot contain multiple key-value pairs unless they are nested" else return obj if [String, Symbol, Array].any? { |klass| obj.is_a? klass } raise "Only strings, symbols, and hashes are allowed as values in the Hash." end end # Usage: # irb&gt; hash_to_eval_chain { :one =&gt; { :two=&gt; { :three =&gt; { :four=&gt; :five } } } } # =&gt; "one.two.three.four.five" </code></pre>
    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. 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