2013-10-28 3 views
0

.txt 파일은 "name"과 "value"(John Anderson, 54)로 구성되어 있으며 ","로 2 열 배열로 나눕니다. 해시로 해봤지만 배열로 어떻게 처리해야할지 모르겠다. 이것은 해시로 처리 한 방법입니다.txt 파일을 두 개의 열로 배열로 배열하는 방법 Ruby

def read_data(file) 
    File.read(file).lines.map{|line| line.chomp.split(', ')} 
end 

my_array_of_values = read_data(path_to_file) 
+1

그냥 사용하는 CSV 모듈을 필요로한다. 문서 : http://ruby-doc.org/stdlib-2.0/libdoc/csv/rdoc/CSV.html –

+1

예상되는 결과는 무엇입니까? [[name1, age1], [name2, age2] ...]? –

+0

예 [[name1, age1], [name2, age2] ...] 제외 – user2871450

답변

0

csv로 모듈은 아마도 갈 방법, 혹은 같은 것입니다. 기본 열 구분 기호는 ,이므로 작동해야합니다.

require 'csv' 

def initialize(file) 
    @file_data = CSV.read(file) 
end 
2

당신은 루비의 CSV 클래스를 사용할 수 있습니다 :

def initialize(file) 
    @file_data ={|h,k|} 
    File.open(file) do |file| 
    file.each_line do |line| 
     line_data = line.split(",") 
     @file_data[line_data[0]]= line_data[1].to_i 
    end 
    end 
end 
0

다음은 내가 수행 한 작업입니다.

은 'CSV'

column0=[] 
column1=[] 
CSV.foreach("test.txt") do |row| 
    column0 << row[0] 
    column1 << row[1] 
    end 

print column1 
print column0 
관련 문제