-1
@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?
4

5 回答 5

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"]] 
于 2012-10-25T22:47:27.893 回答
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]}

无效,我的解决方案没有返回单项数组的数组

于 2012-10-25T22:48:26.403 回答
1
@arr1, @arr2 = @main.transpose.map{|a| a.map{|x| [x]}}
于 2012-10-25T22:49:44.987 回答
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
于 2012-10-25T22:49:31.817 回答
-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]]
于 2012-10-25T22:49:41.673 回答