[英]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. 我创建了一种方法,使您可以在一行中写一个问题,并在下一行中回答,因此该文件在奇数行中只有问题,而在偶数行中只有这些问题的答案,我想添加奇数行(问题)作为数组中的字符串,偶数(答案)也作为字符串但在其他数组中,因此,问题的答案首先位于@questions,而首先位于@answers 。
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. 由于某种原因,当我打印数组时,@ questions显示奇怪的字符,我认为它们是File类的对象,而@answers则为空。
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. 假设您有一个名为foo.txt
的文件, foo.txt
包含交替显示的问题和答案,则可以使用IO::each_line
遍历该文件。
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?
全局变量(包含“读取的最后一个文件的当前输入行号”)和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|
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.