2010-11-28 67 views
1

我正在尝试对Ruby脚本进行一些小改动,以便在运行时指定文件夹位置。在Dir.glob中使用变量

虽然我不是Ruby程序员,但我找不到正确的语法,我确信这将是一件容易的事情。

puts "Enter folder name and press enter: " 
folder = gets 

files = Dir.glob("folder/[0-100]*.txt"); # What is the correct syntax to use, so the content of the variable folder will be used? 

puts files 

回答

1

要插入变量(或任何Ruby表达式)转换成字符串,就可以使用#{}

Dir.glob("#{folder}/[0-100]*.txt") 

另外请注意,由gets返回的字符串将在有一个换行符(\n)结束,当然这在文件夹名称中是无效的。所以你必须使用chomp方法来消除这一点。

+0

如果我直接在Dir.glob中写入文件夹名称,如下所示:Dir.glob(“system_logs/[0-100] *。txt”)将所有日志文件的列表写出来,但使用Dir。 glob(“#{folder}/[0-100] *。txt”)和给定的文件夹名相同,没有任何内容被写出来? – jet8832 2010-11-28 16:38:42