Ruby 反斜杠不是行中的最后一个字符吗?

Ruby 反斜杠不是行中的最后一个字符吗?,ruby,rake-task,rakefile,Ruby,Rake Task,Rakefile,我有一个任务: task :kill_process do current_process_id = Process.pid puts current_process_id ruby_process_command = "ps -ef | awk '{if( $8~" + "ruby && $2!=" + current_process_id.to_s + "){printf(" + "Killin

我有一个任务:

task :kill_process do
  current_process_id = Process.pid
  puts current_process_id
  ruby_process_command = "ps -ef | awk '{if( $8~" + "ruby && $2!=" + current_process_id.to_s + "){printf(" + "Killing ruby process: %s " + "\\n " + ",$2);{system("  + "kill -9 " + "$2)};}};'"
  puts ruby_process_command

system (ruby_process_command)

end
我得到:

awk: cmd. line:1: {if( $8~ruby && $2!=23699){printf(Killing ruby process: %s \n ,$2);{system(kill -9 $2)};}};
awk: cmd. line:1:                                                       ^ syntax error
awk: cmd. line:1: {if( $8~ruby && $2!=23699){printf(Killing ruby process: %s \n ,$2);{system(kill -9 $2)};}};
awk: cmd. line:1:                                                            ^ backslash not last character on line
有什么解决办法吗

我试过这个:

ruby_process_command = "ps -ef | awk '{if( $8~" + '"' + "ruby" + '"' + "&& $2!=" + current_process_id.to_s + "){printf(" + '"' + "Killing ruby process: %s " + "\\n" + '"' + ",$2);{system("  + '"' + "kill -9 " + '"' + "$2)};}};'"

有了这个,它就可以正常工作了,有没有其他好的方法呢?

您当前的解决方案很好,但是可以改进。您可以将字符串插值改为与结合使用,而不是使用来连接字符串

%(…)
创建一个可以使用字符串插值的字符串。在此字符串中,您可以使用
,而无需转义或使用奇怪的技巧。您仍然可以在字符串中使用括号,但必须始终存在匹配对。(如果有不匹配的括号,您可以使用另一个分隔符,例如
%|…|
%{…}
%!
等。)

将此应用于您的命令将如下所示:

ruby_process_command = %(ps -ef | awk '{if( $8~"ruby"&& $2!=#{current_process_id}){printf("Killing ruby process: %s \\n",$2);{system("kill -9 "$2)};}};')
ruby_process_command = %(ps -ef | awk '{if( $8~"ruby"&& $2!=#{current_process_id}){printf("Killing ruby process: %s \\n",$2);{system("kill -9 "$2)};}};')