user3798611
user3798611

Reputation: 25

Ruby: How to add a specific key to every subarray element in the array called and assign it specific value?

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? :)

Upvotes: 2

Views: 219

Answers (2)

bratsche
bratsche

Reputation: 2674

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

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

Upvotes: 1

Omni
Omni

Reputation: 61

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.

Upvotes: 2

Related Questions