如何在ruby中将一个文件读入多个数组

时间:2017-12-19 15:24:38

标签: arrays ruby loops split

我目前正在使用ruby ssh gem,其中有三个变量HOST,USER和PASS。我有一个文件(HOST_USER_PASS.txt)格式如下: HOST,USER,PASS 主机,用户,PASS

我想将这些读入数组,然后在gem中使用这些变量。我目前正在使用带有while循环的split,但到目前为止没有任何工作。

file = File.open("HOST_USER_PASS.txt", 'r') 
# Open file"HOST_USER_PASS.txt", read that file
while !file.eof? #run while end of file is not true
      line = file.readline
      fields = line.split(",") #splits line at the comma
ssh gem etc.
end

问题是,如何将文件读入三个独立的数组?

1 个答案:

答案 0 :(得分:0)

如果我说得对,你的三胞胎是空间分开的。试试这个

file = File.open("HOST_USER_PASS.txt", 'r') 
while !file.eof?
  line = file.readline
  one, two, three = line.split(" ").map { |fields| fields.split(",") }
  # use one, two and three
  # each of these variable is an array with host, user and password
end