1

Is there a built-in which will easily allow you to access the objects within an array and its sub arrays so that one can achieve something along the lines of:

array = [5, 10, [15, 20], 25, [30, 35, 40]
array#method { #block that adds 5} => [10, 15, [20, 25], 30, [35, 40, 45]

I'm unconcerned if it is destructive or not.

1 Answer 1

3

You could use a recursive lambda:

add_five = lambda { |e| e.is_a?(Enumerable) ? e.map(&add_five) : e + 5 }
new_array = array.map(&add_five)

Adjust the e.is_a?(Enumerable) test to match your situation, e.is_a?(Array) would be tighter but possibly unnecessarily so.

Sign up to request clarification or add additional context in comments.

1 Comment

There's also the responds_to?(:map) approach where if it smells duck-like enough you may as well ask it to quack.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.