【问题标题】:How to read one file into multiple arrays in ruby如何在ruby中将一个文件读入多个数组
【发布时间】:2018-06-02 01:48:21
【问题描述】:

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

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

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】:

如果我没记错的话,你的三胞胎是空格分隔的。试试这个

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

【讨论】:

  • 感谢您的回答!总的来说,我非常喜欢红宝石以及计算机科学。抱歉,如果问题不清楚。
  • 我一定是做错了什么。这就是我所做的:HOST = Array.new[0] USER = Array.new[0] PASS = Array.new[0] file = File.open("HOST_USER_PASS.txt", 'r') line = file.readline HOST, USER, PASS = line.split(" ").map { |fields| fields.split(",") }我该如何格式化?
  • file_array:8: 警告: 已经初始化常量 HOST file_array:2: 警告: 以前定义的 HOST 在这里 file_array:8: 警告: 已经初始化常量 USER file_array:3: 警告: 以前定义的 USER在这里 file_array:8: 警告: 已经初始化常量 PASS file_array:4: 警告: 之前的 PASS 定义在这里我得到这些错误
  • 我用你脚本的其余部分更新了我的答案。您现在应该使用变量onetwothree。你试过吗?
  • 我试错了(见上面的行话,有没有办法在 cmets 中格式化代码?)哈哈。让我现在试试这个。
猜你喜欢
  • 2020-05-18
  • 2018-03-18
  • 2015-06-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多