using an enumerable built-in Ruby to access and manipulate nested data

array = [5, 10, [15, 20], 25, [30, 35, 40]

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

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.


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章