2015-12-18 22 views
0

我創建了一種方法,允許您在一行中編寫問題,並在緊接着的下一行中回答問題,以便該文件僅包含問題奇數行和這些問題的答案在偶數行中,我想添加奇數行(問題)作爲字符串在一個數組和偶數(答案)也作爲字符串,但在不同的數組,所以這個問題的答案是位於@questions首位,位於@answers首位。如何將一行文件作爲字符串插入到ruby數組中

這是我的代碼:

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 

出於某種原因,當我打印我的陣列,@questions顯示奇怪的字符,我認爲是類文件的對象,而@answers保持爲空。

非常感謝您閱讀此內容。

回答

1

使用

File.open("questionary.out").each_line do |line| 
+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 } 
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"] 
相關問題