Reputation: 749
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?
Upvotes: 2
Views: 121
Reputation: 5156
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]
Upvotes: 3
Reputation: 7193
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]
Upvotes: 0