Rak*_*dar 1 ruby arrays ruby-on-rails-4
我想从索引位置 0、2 和 4 的每个 arr 数组中选择项目
输入数组
arr = [
["name", "address", "contact", "company", "state"],
["n1", "add1", "c1", "cp1", "s1"],
["n2", "add2", "c2", "cp2", "s2"]
]
Run Code Online (Sandbox Code Playgroud)
输出数组
arr = [
["name", "contact", "company"],
["n1", "c1", "cp1"],
["n2", "c2", "cp2"]
]
Run Code Online (Sandbox Code Playgroud)
作为删除不需要的项目的替代方法,您可以只选择需要的项目。
arr.map{|subarray| subarray.values_at(0, 2, 4) }
# => [["name", "contact", "state"], ["n1", "c1", "s1"], ["n2", "c2", "s2"]]
Run Code Online (Sandbox Code Playgroud)
如果你想采用更通用的方法并且只选择偶数列,你可以这样做
arr.map{|a| a.select.with_index { |e, i| i.even? }}
Run Code Online (Sandbox Code Playgroud)
这使
[["name", "contact", "state"], ["n1", "c1", "s1"], ["n2", "c2", "s2"]]
Run Code Online (Sandbox Code Playgroud)