Ralitza
Ralitza

Reputation: 741

Nested Hash to Nested Array: How to access individual values

I apologize in advance for the newbie question!

I have the following nested hash and want to convert it into a nested array, and be able to access individual values using their indices.

vehicles = {
    car: { type: 'sedan', color: 'red', year: 2007 },
  }

I attempted to do this a couple of different ways below, however, I was not able to access an individual value, like 'sedan' using its index. My questions are 1) How do I access an individual element in each solution? 2) Is it recommended to use .map as I have or to_a for future cases?

 car_array1 = vehicles.to_a
 # => [[:car, {:type=>"sedan", :color=>"red", :year=>2007}]] 

 car_array2 = []
 vehicles.map { |k, v| car_array2 << [k, v] }
 # => [[[:car, {:type=>"sedan", :color=>"red", :year=>2007}]]] 

 puts 'car_array1:'
 p car_array1[0][1]
 # {:type=>"sedan", :color=>"red", :year=>2007}

 puts '-' * 10 

 puts 'car_array2'
 p car_array2[0][1]
 # {:type=>"sedan", :color=>"red", :year=>2007}

Upvotes: 0

Views: 164

Answers (2)

Mark Reed
Mark Reed

Reputation: 95375

Your question is not clear, but based on your comment, you want something like this:

vehicles[:car].to_a

Which yields this:

[[:type, "sedan"], [:color, "red"], [:year, 2007]]

Upvotes: 3

Maxim Pontyushenko
Maxim Pontyushenko

Reputation: 3053

vehicles = {
   car: { type: 'sedan', color: 'red', year: 2007 },
 }

Here you have a hash with nested hash in it: vehicles[:car]. When you attempt to convert it to array with .to_a you convert only higher level of this hash but not nested. To achieve what you want you can convert nested hashes also by doing this:

result = vehicles.to_a.map { |v| v.last.to_a }
=> [[[:type, "sedan"], [:color, "red"], [:year, 2007]]]

Either way you are not doing your solution the right way. It seems too strange and complex, but I don't know your case, so ...

Upvotes: 1

Related Questions