Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 将变量与Dir.glob一起使用_Ruby_Dir - Fatal编程技术网

Ruby 将变量与Dir.glob一起使用

Ruby 将变量与Dir.glob一起使用,ruby,dir,Ruby,Dir,我正在尝试对Ruby脚本进行一个小更改,以便在运行时指定文件夹位置 虽然我不是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 wi

我正在尝试对Ruby脚本进行一个小更改,以便在运行时指定文件夹位置

虽然我不是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
要将变量(或任何ruby表达式)插入字符串,可以使用
#{}

Dir.glob("#{folder}/[0-100]*.txt")
还要注意,
gets
返回的字符串末尾将有一个换行符(
\n
),这在文件夹名称中当然无效。因此,您必须使用
chomp
方法来消除这种情况。

要在字符串中插入变量(或任何ruby表达式),您可以使用
{}

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

还要注意,
gets
返回的字符串末尾将有一个换行符(
\n
),这在文件夹名称中当然无效。因此,您必须使用
chomp
方法来消除这种情况。

如果我直接在Dir.glob中写入文件夹名称,例如:Dir.glob(“system_logs/[0-100]*.txt”),所有日志文件的列表都会被写入,但是使用Dir.glob(“{folder}/[0-100]*.txt”)和给定给gets的相同文件夹名称,什么都没有写出来?@jet:你必须做
folder=gets.chomp
,否则
folder
的末尾会有一个换行符。如果我直接在Dir.glob中写文件夹名,比如:Dir.glob(“system_logs/[0-100]*.txt”),所有日志文件的列表都会被写出来,但是使用Dir.glob(“Dir.glob{folder}/[0-100]*.txt”)与gets使用的文件夹名称相同,没有写入任何内容?@jet:您必须执行
folder=gets.chomp
,否则
folder
将在末尾换行。