tags:

views:

73

answers:

1
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.

+3  A: 

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
mikej
oh thanks mikej u really know ruby very well i also asked about platinfo["telnet_id"] i hope u remember me
Amit singh tomar
mikej the last u told will create different file name likekabab1.txt and kabab2.txt i want to create different filename using loop??
Amit singh tomar
@amit Yes, I remember you from your other question. The examples I gave use a loop to create the different filenames. Please can you explain a bit more if these suggestions still don't do what you want.
mikej
thanks mikej i got what i want .thanks for helping me
Amit singh tomar
but mikej one thing u told i m not able to get you said like we can't access local variable by their name but i do like thata=10puts ai m able to get the value of a by just puuting its namesorry if i m wrong
Amit singh tomar
If I have `a=10` and I have `b="a"` i.e. `b` is a String containing the **name** of another variable then I can't get 10, the **value** of the variable named in `b` without using `eval`. In other languages this is possible e.g in PHP where `$$` can be used to *dereference* a variable. e.g. if I had `$a=10` and `$b="a"` in PHP then `print $$b` would print 10. This is close to what you were trying to do in the original code in your question.
mikej