如何将一行文件作为字符串插入到ruby

时间:2015-12-18 23:21:02

标签: arrays ruby file io

我创建了一个方法,允许你在一行中写一个问题并在紧接的下一行回答,这样该文件只有奇数行中的问题和偶数行中的那些问题的答案,我想将奇数行(问题)作为字符串添加到数组中,偶数(答案)也作为字符串添加,但是在不同的数组中,因此位于@questions的问题的答案位于第一位首先是@answers。

这是我的代码:

def initialize
        @file = File.new("questionary.out", "a")
        @questions = []
        @answers = []
end

def append_to_file

    puts
    puts "PLEASE TYPE THE QUESTION THAT YOU WANT TO ADD"
    puts
    append_question = gets
    @file << append_question

    puts
    puts "PLEASE TYPE IT'S ANSWER"
    puts
    append_answer = gets
    @file << append_answer

    @file.close


    #INSERT INTO THE ARRAYS 
    i = 0
    File.open("questionary.out") do |line|
        i = i+1

        if i % 2 == 0
            @answers << line.to_s
        else 
            @questions << line.to_s
        end
    end
end

出于某种原因,当我打印我的数组时,@ items显示奇怪的字符,我认为它们是类File的对象,而@answers保持为空。

感谢百万读这篇文章。

3 个答案:

答案 0 :(得分:3)

假设您有一个名为foo.txt的文件,其中包含交替行的问题和答案,您可以使用IO::each_line来遍历该文件。

您还可以使用神秘的$.全局变量(其中包含“已读取的最后一个文件的当前输入行号”)和Integer::odd?方法来正确填充数组。例如:

questions = []
answers = []

File.open("foo.txt", "r+").each_line do |l|
  if $..odd?
    questions << l
  else
    answers << l
  end
end

# one-liner for kicks
# File.open("foo.txt", "r+").each_line { |l| $..odd? ? questions << l : answers << l }

答案 1 :(得分:2)

首先,让我们创建一个文件:

q_and_a =<<-END
Who was the first person to set foot on the moon?
Neil Armstrong
Who was the voice of the nearsighted Mr. Magoo?
Jim Backus
What was nickname for the Ford Model T?
Tin Lizzie
END

FName = "my_file"
File.write(FName, q_and_a)
  #=> 175

然后:

questions, answers = File.readlines(FName).map(&:strip).each_slice(2).to_a.transpose
questions
  #=> ["Who was the first person to set foot on the moon?",
  #    "Who was the voice of the nearsighted Mr. Magoo?",
  #    "What was nickname for the Ford Model T?"] 
answers
  #=> ["Neil Armstrong", "Jim Backus", "Tin Lizzie"] 

答案 2 :(得分:1)

使用

File.open("questionary.out").each_line do |line|