Below is the question in my class.
Given the variable
some_array = [[:a, 123], [:b, 456]]
,
convert some_array into this hash:{a: 123, b: 456}
I'm a beginner too, so this may be a little inefficient, but this is how I would explain it (there are simpler methods I'm sure, but since you mentioned this is for a class, I thought I'd explain in long form):
hash={}
some_array.each do |item|
hash[item[0]] = item[1]
end
Just to explain that a bit, I start by creating an empty hash that I will use later.
Then I cycle through some_array
using the each
method. This assigns each element in some_array to the variable item
. Given that some_array is a nested array (which basically means that it is an array of arrays), the item variable will take the value of the inner arrays - for example, item = [:a, 123]
.
Then we can access each element within item
when creating the hash. Following the same example I gave earlier item[0] == :a
and item[1] == 123
.
Then I use some shorthand when creating hashes - i.e. hash[key] = value
. In this case, I want the key to be :a (which is item[0]) and the value to be 123 (which is item[1]). So I can use hash[item[0]] = item[1]
.
Hope that helped!
.to_h
method does exactly this? While it can be educational to implement things like this for academic reasons, the solution is to read the manual and look for what tools are available.
each_with_object
if you want to use that approach. Sometimes what you're doing is valid because you want to perform conversion on each item[1]
.
some_array.to_h