path1="c:/kabab.txt"
path2="c:/kabab2.txt"
for v in 1..2
puts "#{path}"#{v}"
end
I would like to create a file, but I'm not able to do that.
path1="c:/kabab.txt"
path2="c:/kabab2.txt"
for v in 1..2
puts "#{path}"#{v}"
end
I would like to create a file, but I'm not able to do that.
In Ruby you can't retrieve the value of a local variable from its name using the approach you've tried. There is instance_variable_get
for instance variables but there isn't an equivalent for local variables as far as I know.
"path#{v}"
is a string containing the name of your variable so if you evaluate that using eval
the result from the eval will be the value of the variable. Therefore you could do something like:
filename = eval("path#{v}")
open(filename, 'w')
but you always need to be careful when using eval
because of potential security issues.
Instead, I would put the list of files in an array
paths = ["c:/kabab.txt", "c:/kabab2.txt"]
and do:
paths.each do |path|
f = open(path, 'w')
# use file here
end
or if all the files share a common prefix and extension then something like:
prefix = "c:/kabab"
extension = ".txt"
for v in 1..2
filename = "#{prefix}#{v}#{extension}"
# use filename here
end