2

I want to apply a function to each of the values at all levels of the array:

arr = [[1,2,3],[1,2,3],[[1,2],[1,2]],1,2,3]

for example, multiply all the values by 3, and map it in the same format as before so I get:

arr = [[3,6,9],[3,6,9],[[3,6],[3,6]],3,6,9]

What would be the best way to go about this?

4
  • 2
    Recursion seems to be your best bet. Commented Jul 16, 2015 at 14:25
  • thanks, any ideas on how I would go about that ? Commented Jul 16, 2015 at 14:28
  • See my answer for details. Commented Jul 16, 2015 at 14:38
  • Thanks, that does exactly what I want! Commented Jul 16, 2015 at 15:28

2 Answers 2

3

Use recursion. Create a method that will call itself if the element is array, do your calculation if it is not.

def walk_array(array)
  array.map do |element|
    if element.is_a?(Array)
      walk_array(element)
    else
      element * 3
    end
  end
end

arr = [[1,2,3],[1,2,3],[[1,2],[1,2]],1,2,3] 
# => [[1, 2, 3], [1, 2, 3], [[1, 2], [1, 2]], 1, 2, 3]

walk_array(arr) 
# => [[3, 6, 9], [3, 6, 9], [[3, 6], [3, 6]], 3, 6, 9]
Sign up to request clarification or add additional context in comments.

Comments

0

If you're open to using a gem, I wrote a module that provides exactly this functionality: https://github.com/dgopstein/deep_enumerable

>> require 'deep_enumerable'
>> arr = [[1,2,3],[1,2,3],[[1,2],[1,2]],1,2,3]

>> arr.deep_map_values{|x| x*3}
=> [[3, 6, 9], [3, 6, 9], [[3, 6], [3, 6]], 3, 6, 9]

Comments

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.