Note that there are some explanatory texts on larger screens.

plurals
  1. PONested hash iteration: How to iterate a merge over an ( (array of hashes) within a hash )
    primarykey
    data
    text
    <p>I'm trying to do as the title says. Here is my code:</p> <pre><code>school.each { |x| school[:students][x].merge!(semester:"Summer") } </code></pre> <p>I think I pinpointed the problem to the "[x]" above. If I substitute an array position such as "[2]" it works fine. How can make the iteration work?</p> <p>If the info above is not enough or you'd like to offer a better solution, please see the details below. Thanks!</p> <hr> <p>The error message I get:</p> <p><strong>file.rb:31:in <code>[]': no implicit conversion of Array into Integer (TypeError) from file.rb:31:in</code>block in ' from file.rb:31:in <code>each' from file.rb:31:in</code>'</strong></p> <p>The nested hash below before alteration:</p> <pre><code>school = { :name =&gt; "Happy Funtime School", :location =&gt; "NYC", :instructors =&gt; [ {:name=&gt;"Blake", :subject=&gt;"being awesome" }, {:name=&gt;"Ashley", :subject=&gt;"being better than blake"}, {:name=&gt;"Jeff", :subject=&gt;"karaoke"} ], :students =&gt; [ {:name =&gt; "Marissa", :grade =&gt; "B"}, {:name=&gt;"Billy", :grade =&gt; "F"}, {:name =&gt; "Frank", :grade =&gt; "A"}, {:name =&gt; "Sophie", :grade =&gt; "C"} ] } </code></pre> <p>I'm trying to append :semester=>"Summer" to each of the last four hashes. Here is what I'm trying to go for:</p> <pre><code># ...preceding code is the same. Changed code below... :students =&gt; [ {:name =&gt; "Marissa", :grade =&gt; "B", :semester =&gt; "Summer"}, {:name=&gt;"Billy", :grade =&gt; "F", :semester =&gt; "Summer"}, {:name =&gt; "Frank", :grade =&gt; "A", :semester =&gt; "Summer"}, {:name =&gt; "Sophie", :grade =&gt; "C", :semester =&gt; "Summer"} ] } </code></pre>
    singulars
    1. This table or related slice is empty.
    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.
 

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