Ruby 多重';执行官';和';打印';一个文件中的命令

Ruby 多重';执行官';和';打印';一个文件中的命令,ruby,Ruby,混合使用exec命令和print命令时,使用分号无效。最好的方法是什么 print "Initializing tests...\n" print 'Testing 00_hello\n' exec 'cd 00_hello; rspec hello_spec.rb; cd ..' print 'Testing 01_temperature\n' exec 'cd 01_temperature; rspec temperature_spec.rb; cd ..' 如果您问为什么文件的最后两

混合使用
exec
命令和
print
命令时,使用分号无效。最好的方法是什么

print "Initializing tests...\n"
print 'Testing 00_hello\n'
exec  'cd 00_hello; rspec hello_spec.rb; cd ..'
print 'Testing 01_temperature\n'
exec  'cd 01_temperature; rspec temperature_spec.rb; cd ..'

如果您问为什么文件的最后两行不会执行,那与您使用分号无关<代码>执行替换当前进程。调用
exec
后的任何代码都不会执行,因为只要调用
exec
,进程就会停止执行。在大多数情况下,您希望使用
system
,而不是
exec

我还应该指出,没有必要在给
exec
system
的命令末尾执行
cd..
cd
只影响它在其中执行的shell以及从该shell派生的任何进程,而不影响父进程。因此,如果您在shell命令中使用
cd
,您的ruby进程将不会受到影响,因此无需
cd
返回


哦,您不能在单引号字符串中使用转义序列,如
\n
,它们只会显示为反斜杠,后跟字母n。如果要使用
\n
,则需要使用双引号字符串。如果您使用
put
而不是
print
,它会自动在末尾插入换行符,因此您根本不需要
\n

如果您问为什么文件的最后两行不会执行,这与您使用分号无关<代码>执行替换当前进程。调用
exec
后的任何代码都不会执行,因为只要调用
exec
,进程就会停止执行。在大多数情况下,您希望使用
system
,而不是
exec

我还应该指出,没有必要在给
exec
system
的命令末尾执行
cd..
cd
只影响它在其中执行的shell以及从该shell派生的任何进程,而不影响父进程。因此,如果您在shell命令中使用
cd
,您的ruby进程将不会受到影响,因此无需
cd
返回


哦,您不能在单引号字符串中使用转义序列,如
\n
,它们只会显示为反斜杠,后跟字母n。如果要使用
\n
,则需要使用双引号字符串。如果您使用
put
而不是
print
,它将自动在末尾插入换行符,因此您根本不需要
\n

您将
exec
系统
混在一起
exec
将当前进程替换为运行参数的命令。如果要运行该文件并等待它并获得控制权,则需要使用
system

print "Initializing tests...\n"
print 'Testing 00_hello\n'
system  'cd 00_hello; rspec hello_spec.rb; cd ..'
print 'Testing 01_temperature\n'
system  'cd 01_temperature; rspec temperature_spec.rb; cd ..'

你把
exec
system
搞混了
exec
将当前进程替换为运行参数的命令。如果要运行该文件并等待它并获得控制权,则需要使用
system

print "Initializing tests...\n"
print 'Testing 00_hello\n'
system  'cd 00_hello; rspec hello_spec.rb; cd ..'
print 'Testing 01_temperature\n'
system  'cd 01_temperature; rspec temperature_spec.rb; cd ..'

将字符串放在反引号(`)之间将作为系统命令执行该字符串

例如,试试这个

print "Initializing tests...\n"
print 'Testing 00_hello\n'
`cd 00_hello; rspec hello_spec.rb; cd ..`
print 'Testing 01_temperature\n'
`cd 01_temperature; rspec temperature_spec.rb; cd ..`

将字符串放在反引号(`)之间将作为系统命令执行该字符串

例如,试试这个

print "Initializing tests...\n"
print 'Testing 00_hello\n'
`cd 00_hello; rspec hello_spec.rb; cd ..`
print 'Testing 01_temperature\n'
`cd 01_temperature; rspec temperature_spec.rb; cd ..`

Backticks以字符串形式返回命令的输出,而不打印它。如果这是您想要的,那么这很好,但是在您的代码中,您没有对返回的字符串执行任何操作,因此输出被丢弃。我很确定OP希望看到输出。@Sachin有没有办法用反勾号进行插值?@dresdin:是的,像在字符串中一样使用
{}
。反勾号将命令的输出作为字符串返回,而不打印它。如果这是您想要的,那么这很好,但是在您的代码中,您没有对返回的字符串执行任何操作,因此输出被丢弃。我很确定OP想要看到输出。@Sachin有没有办法用反勾号进行插值?@dresdin:是的,像在字符串中一样使用
{}