[英]ruby - help need to convert an array to a specific type of array of arrays, duplicating the keys as [key, value] int he list
I want to convert and array into a specific type of array of arrays. 我想将数组转换为特定类型的数组。
array = ["Project", "Publication"] array = [“ Project”,“ Publication”]
into 进入
array_of_arrays =[["Project", "Project"], ["Publication", "Publication"] ] array_of_arrays = [[“ Project”,“ Project”],[“ Publication”,“ Publication”]]
The array is not just limited to size two. 该数组不仅限于大小2。 Its a growing list , so looking for some function to convert it to array_of_arrays.
它的列表越来越多,因此需要寻找一些函数将其转换为array_of_arrays。
Appreciate any help. 感谢任何帮助。
def replicate(arr, n)
arr.map { |e| [e]*n }
end
replicate(["Project", "Publication"], 2)
#=> [["Project", "Project"], ["Publication", "Publication"]]
replicate(["Project", "Publication"], 3)
#=> [["Project", "Project", "Project"], ["Publication", "Publication", "Publication"]]
replicate([["ProjectA", "ProjectB"], "Publication"], 2)
#=> [[["ProjectA", "ProjectB"], ["ProjectA", "ProjectB"]], ["Publication", "Publication"]
This is something map can handle quite easily. 地图可以很轻松地处理此问题。
a = ["Project", "Publication"]
a.map{|x| [x,x]}
#=> [["Project", "Project"], ["Publication", "Publication"]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.