Assume, i got the following file (input.txt):
name = "Peter"
age = 26
family_status = married
Mentioned lines can be stored in a random order, lie:
family_status = married
name = "Peter"
age = 26
In my program I also have variables family_status, age and name. How do I in a single cycle read those lines from file and assign correspond variables with the values?
Setting Variables
This depends on several facts.
String,Symbol, whatever)I assume you are using instance variables for this:
If you are not using instance variables you have to change the
instacne_variable_setandvar= :"@...line to you needs. This code has the following advantages:reading as YAML
If your needs are not as specific as in your question I would go an entirely different approach to this.
I would write the
input.txtas a yaml file. In yaml syntax it would look like this:You can read it with:
Be carefull if you don’t control the
input.txtfile, you don’t control which types the data will have. I would name the fileinput.yamlinstead ofinput.txt. If you want to know more, about how to write yaml files have a look at: http://yaml.kwiki.org/?YamlInFiveMinutes. More infos about yaml and ruby can be found at http://www.ruby-doc.org/stdlib/libdoc/yaml/rdoc/index.html.