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

问题描述 投票:-3回答:1

我目前正在使用ruby ssh gem,我有三个变量HOST,USER和PASS。我有一个文件(HOST_USER_PASS.txt)格式如下:HOST,USER,PASS HOST,USER,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

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

arrays ruby loops split
1个回答
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
© www.soinside.com 2019 - 2024. All rights reserved.