Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby

Shaunda King
Shaunda King
1,871 Points

Converting an array into a single array

I need some help. I'm brand new to codes and I'm learning Ruby right now. I have to turn this array into a single array. Here's the initial array:

array = [["a", "b"], ["c", "d"], ["e", "f"], ["g", "h"], ["i", "j"]]

This is the desired conversion:

["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"]

So far I have this:

index = 0

5.times do p array[index] index = index + 1 end

I know that I have to add a loop, but I can't figure this out for the death of me. Thanks!

1 Answer

Ling Lei
Ling Lei
6,099 Points

I'm not 100% sure on this one. But you try do the following.

array = [["a", "b"], ["c", "d"], ["e", "f"], ["g", "h"], ["i", "j"]]
arr = Array.new
array.each  {|a| array[a].each{|b|arr.push(b)}}

my syntax might be wrong here, so i'll explain it as well.

You could create a new array and iterate over the original array and then iterate over the element arrays "["a","b"]" and push them to the new array.