简体   繁体   中英

how to insert a line of a file as a string into an array in ruby

i created a method that allows you to write a question in one line and it's answer in the immediately next line, so that file has only questions in the odd lines and answers to those questions in the even lines, i want to add the odd lines (questions) as strings in an array and the even ones (answers) also as strings but in a different array, so the answer of the question that is located at @questions in the first place, is located at @answers in the first place.

This is my code:

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

For some reason, when i print my arrays, @questions shows strange characters, which i think are an object of the class File, while @answers stays empty.

Thanks a million for reading this.

Assuming you had a file called foo.txt with questions and answers on alternating lines, you can use IO::each_line to iterate through the file.

You could also use the cryptic $. global variable (which contains the "current input line number of the last file that was read") and Integer::odd? method to appropriately populate your arrays. For example:

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 }

First, let's create a file:

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

Then:

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"] 

采用

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM