从Ruby调用Shell命令

如何从Ruby程序内部调用Shell命令?然后如何将这些命令的输出返回到Ruby?

解决方案

我喜欢的方法是使用%x字面量,这使得在命令中使用引号变得容易(并且易于阅读!),如下所示:

directorylist = %x[find . -name '*test.rb' | sort]

在这种情况下,它将用当前目录下的所有测试文件填充文件列表,我们可以按预期进行处理:

directorylist.each do |filename|
  filename.chomp!
  # work with file
end

我们还可以使用反引号运算符(`),类似于Perl:

directoryListing = `ls /`
puts directoryListing # prints the contents of the root directory

如果我们需要简单的东西,则非常方便。

日期:2020-03-24 10:26:48 来源:oir作者:oir