Straighten Array of Arrays

Hello,

I have an array of arrays like this:

[
[‘one’, ‘two’, ‘three’],
[‘four’, ‘five’, ‘six’, ‘seven’]
]

that I need to straighten out into this:

[
‘one’,
‘two’,
‘three’,
‘four’,
‘five’,
‘six’,
‘seven’
]

but I don’t know how.

i think you want Array#flatten…

crooked = [
[‘one’, ‘two’, ‘three’],
[‘four’, ‘five’, ‘six’, ‘seven’]
]

straightened = crooked.flatten

p straightened

=> [“one”, “two”, “three”, “four”, “five”, “six”, “seven”]

  • j

Agent M. wrote in post #1005553:

Hello,

And of course if flatten() didn’t exist, you could always do something
like this:

data = [
[‘one’, ‘two’, ‘three’],
[‘four’, ‘five’, ‘six’, ‘seven’]
]

results = []

data.each do |arr|
arr.each do |word|
results << word
end
end

p results

–output:–
[“one”, “two”, “three”, “four”, “five”, “six”, “seven”]

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs