【问题标题】:Read a file with ruby to two variables directly用ruby直接读取文件到两个变量
【发布时间】:2023-03-16 13:35:01
【问题描述】:

使用How can I read a file with Ruby?,读取文件然后一行一行地打印它。

但我的要求不同。

我有一个类似千行内容的txt文件。

ABC 123
XYZ 234

所以使用下面的代码,我可以打印整行。

File.open("input.txt", "r") do |infile|
    while (line = infile.gets)
        puts "#{counter}: #{line}"
        counter = counter + 1
    end
end

但我需要将 column1 分配给 A,将 column2 分配给 B:

File.open("input.txt", "r").each_line do |A B|
        puts "#{A} has the value of #{B}"
end

我该怎么做。

一般来说,我需要一个像 bash 脚本一样的 ruby​​ 函数:

#!/usr/bin/env bash

while read A B 
do
  echo "$A has the value of $B"
done < input.txt

【问题讨论】:

    标签: ruby


    【解决方案1】:

    你想要这样的东西吗?

    File.open("my/file/path", "r").each_line do |line|
      var1, var2 =line.split(" ")
    end
    

    如果没有,请查看使用 CSV 库: http://www.sitepoint.com/guide-ruby-csv-library-part/

    【讨论】:

      【解决方案2】:

      你可以这样做:

      fname = 'tmp'
      str =<<_
      cat 1
      dog 2
      pig 3
      _
      
      File.write(fname, str)
      
      IO.foreach(fname) {|l| puts "%s has the value of %s" % l.split }
      cat has the value of 1
      dog has the value of 2
      pig has the value of 3
      

      【讨论】:

        【解决方案3】:

        只要您不需要存储这些值以供将来参考,您就可以很容易地在空间处分割行并将其用作数组来提取两个变量。此外,如果您对每一行进行迭代,它将为您节省循环中出现小错误的可能性,但您始终可以用循环替换它。

        File.open("my/file/path", "r").each_line do |line|
          vars=line.split(" ")
          puts "#{vars[0]} has the value of #{vars[1]}"
        end
        

        【讨论】:

        • 拆分函数是个好主意,有没有我可以使用的“字段分隔符”,例如空格?否则,它可能尚未拆分为 vars[1]。
        • 我还是更喜欢它可以直接分配给两个变量,用whitespace分割,不确定ruby是否已经有这个功能。
        • 如果你想要 2 个变量,你可以这样做 stackoverflow.com/questions/9576407/…
        • 似乎 line.split() 已经将空格作为空格。我添加了更多的空格和制表符,没有影响并得到相同的结果。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-12-15
        • 2022-01-02
        • 2017-05-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-24
        相关资源
        最近更新 更多