制作二维数组

时间:2012-12-11 07:21:42

标签: ruby

我的数组是["Mehmet,1,3,0,0,0\n", "Veli,2,1,2,0,2\n", "Ali,0,1,1,0,0\n"]

我希望声明二维数组,例如array[1][2],其中第一维为name,第二维为note。

我该怎么做?

Text.txt是

穆罕默德,1,3,0,0,0 王梦奎,2,1,2,0,2 阿里,0,1,1,0,0

我的代码是

filename = "text.txt"
results = []
File.new(filename, "r").each { |line| results << line }

results.inject([]){|ar,s|
ar.concat(s.split(/,/))}


puts results.inspect

4 个答案:

答案 0 :(得分:1)

array = File.read("text.txt").split
# => ["Mehmet,1,3,0,0,0", "Veli,2,1,2,0,2", "Ali,0,1,1,0,0"]

array.map { |ar| x, *xs = ar.split(","); [x, xs.join] }
# => [["Mehmet", "13000"], ["Veli", "21202"], ["Ali", "01100"]]

或者,如果您不想加入第二个子阵列

array.map { |ar| x, *xs = ar.split(","); [x, xs] }
# => [["Mehmet", ["1", "3", "0", "0", "0"]],
#     ["Veli", ["2", "1", "2", "0", "2"]],
#     ["Ali", ["0", "1", "1", "0", "0"]]]

答案 1 :(得分:1)

修改您首次发布的集:

data = ["Mehmet,1,3,0,0,0\n", "Veli,2,1,2,0,2\n", "Ali,0,1,1,0,0\n"]
data = data.map {|x| y = x.split(","); [y.delete_at(0), y] }

=> [["Mehmet", ["1", "3", "0", "0", "0\n"]],
 ["Veli", ["2", "1", "2", "0", "2\n"]],
 ["Ali", ["0", "1", "1", "0", "0\n"]]]

puts data[0][0] 
=> Mehmet

答案 2 :(得分:0)

2d数组表示数组数组。所以,简单地说就像:

board = [ [ 1, 2, 3 ],[ 4, 5, 6 ]]

答案 3 :(得分:0)

你在找这样的东西吗?

array = ["Mehmet,1,3,0,0,0\n", "Veli,2,1,2,0,2\n", "Ali,0,1,1,0,0\n"]
new_array = array.map do |elem|
  splited = elem.split(/[,\s]/)
  [splited.shift, splited]
end
# => [["Mehmet", ["1", "3", "0", "0", "0"]],
#     ["Veli", ["2", "1", "2", "0", "2"]],
#     ["Ali", ["0", "1", "1", "0", "0"]]]