Eleizson
Eleizson

Reputation: 1

Name new file from variable

I've got a variable, the contents of which vary as the program progresses. I need a txt file created, pulling its name from the variable (whatever it happens to hold at the time).

I can't seem to do this.

Currently my code is

 $var="filename"
    f = File.open ("#$var.txt")

Other permutations of 'File.' fail to read the variable contents, just naming the file literally as '$var.txt'. Meanwhile with File.open, I get a 'No such file or directory' error. So I tried

$var="filename"    
   f = File.open ("#$var.txt", "w")

And the error is gone, but replaced with

syntax error, unexpected ',', expecting ')'

*Okay so as soon as I finished this, I fixed the thing just by setting w+ outside the parentheses. Seems obvious in hindsight but I guess my question now is why every blasted piece of documentation anywhere gave me the wrong syntax...

Upvotes: 0

Views: 41

Answers (1)

Daniel Viglione
Daniel Viglione

Reputation: 9407

I would put the opening and closing parenthesis next to the method call:

f = File.open("#{$var}.txt", "w")

Rather than this:

f = File.open ("#{$var}.txt", "w")

Remember that () has high operator precedence level and could be used to evaluate an expression and then try to pass the result to the method open.

Upvotes: 1

Related Questions