Adding values to a hash (from an array) through a while loop

Hi All,

Any suggestions how to add values to a hash, copied from an array, using
a while loop to iterate over the hash’s keys?

Array = [“Bob S.”, 1986, “New York”, “Washington”, [“Sports”,
“Photography”, “Reading”, “Cooking”]

Hash = {“Name” => nil, “DOB” => nil, “City” => nil, “Born” => nil,
“Hobbies” => nil }

Thanks

You have two choices here:

If you can handle the values of the Hash without having to specify order
you can just use Hash.values

or add them to the existing Array using something like:

Array +=
[Hash[‘Name’],Hash[‘DOB’],Hash[‘City’],Hash[‘Born’],Hash[‘Hobbies’]||[]]
#assuming that hobbies should always be an array if empty.

Not sure how useful a while loop would be given the sparse example
you’ve given. Hash.values

Best wishes,
Paul

Thanks. I’m very new to this so I really appreciate the help.

The exercise prompts you to use the .key() method and a while loop that
will iterate over the hash’s keys, copying over the values from the
array. I don’t think its the best way to do it but I think they want to
test these skills.

I got this far (see below) but realise that I don’t know how to copy the
values from the array into the hash.

index = 0
while index < hash.count()
puts “#{hash.keys}: #{array}”
index += 1
end