@main = connection.execute("select code_ver, comment from mastertest
@main包含这样的内容:
{ [2.1, abcd],
[3.0, xyz],
[2.0, pqr] }
我想将此数组拆分为2个数组,以便:
@arr1 = {[2.1],
[3.0],
[2.0]}
@arr2 = {[abcd],
[xyz],
[pqr]}
我这样做是为了从另一个数组中复制一个数组:
@arr1 = Array.new
@main.each { |r| @arr1.push(r[0]) }
Can something be done here itself to split it how I want it?
答案 0 :(得分:3)
假设上面的“数组”中有一些拼写错误,一个简单的map
就可以解决问题:
> @main = [[2.1, 'abcd'], [3.0, 'xyz'], [2.0, 'pqr']]
# => [[2.1, "abcd"], [3.0, "xyz"], [2.0, "pqr"]]
> @arr1 = @main.map {|y|[y[0]]}
# => [[2.1], [3.0], [2.0]]
> @arr2 = @main.map {|y|[y[1]]}
# => [["abcd"], ["xyz"], ["pqr"]]
您也可以查看transpose
:
> @main.transpose
# => [[2.1, 3.0, 2.0], ["abcd", "xyz", "pqr"]]
答案 1 :(得分:1)
ar1 = Array.new
ar2 = Array.new
[ [2.1, abcd], [3.0, xyz], [2.0, pqr] ].each do |val|
ar1 << val[0]
ar2 << val[1]
end
编辑:
如上所述:
{[2.1, abcd], [3.0, xyz], [2.0, pqr]}
无效,我的解决方案是不返回单项数组数组
答案 2 :(得分:1)
@arr1, @arr2 = @main.transpose.map{|a| a.map{|x| [x]}}
答案 3 :(得分:0)
简单的方法是执行两个map
操作:
@arr1 = @main.map(&:first)
@arr2 = @main.map(&:last)
但如果@main
很大,这是一个坏主意,因为它遍历数组两次。在那种情况下:
@arr1 = []
@arr2 = []
@main.each do |item|
@arr1 << item.first
@arr2 << item.last
end
transpose
可以在单行
@arr1, @arr2 = @main.transpose
答案 4 :(得分:-1)
也许使用#transpose
方法的东西:
main = [[2.1,'abcd'],[3.0,'xyz'],[2.0,'pqr']]
p main.transpose.first #=> [2.1, 3.0, 2.0]
或者,如果结果应该是单元素数组:
main = [[2.1,'abcd'],[3.0,'xyz'],[2.0,'pqr']]
p main.transpose.first.map { |e| [e] } #=> [[2.1], [3.0], [2.0]]