2

I'm not sure if I understood the task correctly, but it's written: "add a key to every worker in the workers array called "season" and assign it the value "winter""

hash1 = { 
  :title => "MegaCorporation",
  :location => "Europe",
  :supervisors => [ 
    {:name=>"Bill", :about=>"blah blah blah 1" },
    {:name=>"John", :about=>"blah blah blah 2"},
    {:name=>"Tiffany", :about=>"blah blah blah 3"}
  ],
  :workers => [ 
    {:name => "Alex", :level => "A"},
    {:name=>"Anna", :level => "B"},
    {:name => "Ashley", :level => "C"},
    {:name => "Mike", :level => "B"}
  ]
}

So my code is:

hash1[:workers].each { |key,value| key["season"] = "winter"}

Did I do what I was asked correctly or what? :)

3
  • 2
    btw, not that this is really related to your question, but your variable array1 is not an array, it's a hash. Kind of a minor nitpick, but it could make your code slightly more understandable/readable. Commented Jul 3, 2014 at 2:27
  • I corrected the code, thanks! :) Commented Jul 3, 2014 at 13:38
  • Welcome to SO. This question is strange. It could easily be validated with the interpreter. Why haven't you tried in the interpreter instead of asking it here? Commented Jul 3, 2014 at 16:46

2 Answers 2

2

Personally I would have done it like this:

hash1[:workers].each { |worker| worker[:season] = "winter"}

Makes sense to read and doesn't defer responsibility to other functions that you might not understand.

Sign up to request clarification or add additional context in comments.

1 Comment

Great, thank you! I think this variant is the best as it indeed shows the logic without any extra methods involved.
1

Yeah, what you did should work. Another way you might have done it could be:

hash1[:workers].each { |h| h.merge!(season: 'winter') }

1 Comment

Don't yet have enough reputation to give you, so just thanks! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.