-2

私の配列は["Mehmet,1,3,0,0,0\n", "Veli,2,1,2,0,2\n", "Ali,0,1,1,0,0\n"].

名前の最初の次元とメモの2番目の次元のように、 2次元配列を宣言したいと思います。array[1][2]

どうすれば作れますか?

Text.txt は

Mehmet,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

4 に答える 4

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"]]

または、2番目のサブアレイに参加したくない場合

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"]]]
于 2012-12-11T07:25:37.853 に答える
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
于 2012-12-11T07:42:53.140 に答える
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"]]]
于 2012-12-11T07:41:58.943 に答える
0

2D配列は、配列の配列を意味します。したがって、単純に次のようになります。

board = [ [ 1, 2, 3 ],[ 4, 5, 6 ]]
于 2012-12-11T07:24:51.273 に答える