我有一个非常基础的问题。我正在运行一个Ruby脚本来访问Linux中一个目录的内容。当执行Ruby脚本时,该目录被通过命令行传递。
我的问题是如何在Ruby命令中使用命令行参数?
我已经设置了如下:
usrDirectory = ARGV[0]
lsCmd = `ls -l`
我需要使用类似于"ls -l usrDirectory"的命令,我能直接像这样插入命令吗?
ls
的输出显示在标准输出中,可以使用以下方式使其更加简洁:system("ls", "-l", dir)
你应该能够在不使用 shell 的情况下获得你想要的东西,例如:
usr_dir = "/tmp"
files = Dir["#{usr_dir}/*"]
p files
?
您可以在命令字符串中使用表达式扩展和转义序列:
lsCmd = `ls -l #{usrDirectory}`
你有两个选择。你可以:
lsCmd = `ls -l #{usrDirectory}`
或者
command = "ls -l " + usrDirectory
lsCmd = %x[ #{command} ]
system
,应该使用多参数版本:system('ls', '-l', dir)
。 - mu is too short