Home How do i read lines in txt and use them in a method for ruby, exactly as the text is?
Reply: 1

How do i read lines in txt and use them in a method for ruby, exactly as the text is?

Mads Enoch
Mads Enoch Published in 2017-12-07 11:23:09Z
class Test

  def self.take_test( question, options, answer )
    puts question
    options.each_with_index { |option, idx| puts "#{ idx + 1 }: #{ option}" }
    print "Answer: "
    reply = gets.to_i
    if answer == reply
      puts "Correct!"
      puts "Wrong. The answer is: " + answer.to_s

file = File.open("Matematik.txt", "r")

This is what i tried to do:

  IO.foreach("Matematik.txt") { |line| Test.take_test(line) }

This is how the questions are set up in the file:

'What is 2+2?', [ '2', '3', '4', '5', ], 4

'What is 3+3?', [ '3', '6', '9', ], 6

I get the error: take_test wrong number of arguments given (given 1, expected 3) (ArgumentError)

It seems like it reads the line like 1 argument. Is there a way to read the lines exactly as i stands, and input it like this?:

#Test.take_test('What is 2+2?', [ '2', '3', '4', '5', ], 4)
Amadan Reply to 2017-12-07 11:46:00Z

In theory, yes, with eval("Test.take_test(#{line})"). However, eval is evil, and to be avoided if at all possible.

It would be much easier if you changed your file format so you can deconstruct it easily. (It is not impossible with your format, it's just you have a lot of unnecessary work, when compared to a simpler format.) For example, given lines formatted like CSV:

"What is 2+2?",2,3,4,5,4

it is very easy to do the following:

require 'csv'

Question = Struct.new(:text, :options, :answer)

questions = CSV.read("Mathematik.csv").map { |text, *options, answer|
  Question.new(text, options, answer.to_i)

# => "What is 3+3?"

# => ["2", "3", "4", "5"]

# => 4
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.336869 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO