OmerR
OmerR

Reputation: 59

Save variables to a file

I'm working on a Ruby project on RHEL6 at work which includes a quiz. The answers are bool variables that change if your answer is correct or not.

Atm I'm trying to add a save option for the bools, but I'm encountering a problem. How can I access the variables written in the code from a method?

code sample:

@inf_cmd_q1 = true
@inf_cmd_q2 = false
@inf_cmd_q3 = true
@inf_cmd_q4 = false
@inf_cmd_q5 = true
@inf_cmd_q6 = true
@inf_cmd_q7 = false
@inf_cmd_q8 = true
@inf_cmd_q9 = true
@inf_cmd_q10 = false

def save(fname)
    for i 1..10
        system("echo #{@inf_cmd_q#{i}} >> /quiz/#{fname}")
    end
end

I know it won't work, but I'm having hard time figuring how to make it work, plus I never worked with instance variables, because I just started using Ruby.

any advices?

Upvotes: 0

Views: 195

Answers (1)

Lukas Baliak
Lukas Baliak

Reputation: 2869

You can print instance variables dynamicly.

  1.upto 10 do |i|
    puts "#{self.instance_variable_get("@inf_cmd_q#{i}")}"
  end

If you need to save data to File, use File methods. BTW: for saving data you can use JSON data structure.

Upvotes: 2

Related Questions