-1

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}

4

2 Answers 2

4

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!

3
  • Why would you do it that way when the .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.
    – tadman
    Jan 24, 2017 at 18:32
  • Thank you @tadman , since it seems like a basic problem, I figured he must have just started out and would appreciate the explanation. But your comment is valid too, using the tools available is just as important. Jan 24, 2017 at 18:38
  • I'm not trying to slag you here, just saying that in production code you should do it by the book. As always, yearn to understand more and do experiment. For example, your code can be improved by using 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].
    – tadman
    Jan 24, 2017 at 18:48
1

To convert in to hash simply use .to_h method

some_array.to_h

Not the answer you're looking for? Browse other questions tagged or ask your own question.