RyanScottLewis
RyanScottLewis

Reputation: 14016

Multidimensional each

How would I do something like below?

[
    'foo'
    ['bar', 'baz'],
    [
        'one',
        ['two', 'three']
    ]
].each { |word| puts word }

# I want this to return:

foo
bar
baz
one
two
three

Upvotes: 5

Views: 345

Answers (3)

Evan Senter
Evan Senter

Reputation: 247

If you don't want to flatten the array and still achieve the desired functionality, you can do something like:

irb(main):016:0> array = [1, [2, 3], [4, [5, 6]]]
=> [1, [2, 3], [4, [5, 6]]]
irb(main):017:0> (traverser = lambda { |list| list.respond_to?(:each) ? list.each(&traverser) : puts(list) })[array]
1
2
3
4
5
6
=> [1, [2, 3], [4, [5, 6]]]

Upvotes: 2

Carson Myers
Carson Myers

Reputation: 38564

Could you use flatten?

[
    'foo'
    ['bar', 'baz'],
    [
        'one',
        ['two', 'three']
    ]
].flatten.each { |word| puts word }

flatten will return a copy of the array, so the original won't be modified.
It's also fully recursive so it doesn't matter how many arrays-within-arrays you have.

Upvotes: 3

perimosocordiae
perimosocordiae

Reputation: 17797

The easiest way:

words = ['foo',['bar', 'baz'],['one',['two', 'three']]]
words.flatten.each{ |word| puts word }

Upvotes: 2

Related Questions