2

I have a string and a variable, i want to use this varaible inside this string, so it will take that value before converting it to string:

current_process_id = 222
ruby_command = %q(ps -x | awk '{if($5~"ruby" && $1!= %d ){printf("Killing ruby process: %s \n",$1);}};')
puts ruby_command

I tried :

current_process_id = 222
ruby_command = %q(ps -x | awk '{if($5~"ruby" && $1!= %d ){printf("Killing ruby process: %s \n",$1);}};') % [current_process_id]
puts ruby_command

But this is giving error :

main.rb:2:in `%': too few arguments (ArgumentError)

I tried :

awk_check = %q(ps -x | awk '{if) + "(" + %q($5~"ruby" && $1!=)
print_and_kill = %q({printf("Killing ruby process: %s \n",$1);{system("kill -9 "$1)};}};')
ruby_process_command = awk_check  + current_process_id.to_s + ")" + print_and_kill
puts ruby_process_command

This works fine for me. But the way i did is not clean.

I'm looking for more cleaner way to do it.

Nitin Singhal
  • 215
  • 2
  • 11
  • 2
    You seem to be asking the [same](https://stackoverflow.com/q/62536123/477037) [question](https://stackoverflow.com/q/62532464/477037) [again](https://stackoverflow.com/q/62514804/477037) [and](https://stackoverflow.com/q/62509528/477037) [again](https://stackoverflow.com/q/62464476/477037) :-) I know these are different aspects, but maybe you should take the time to ask about / explain the problem as a whole? – Stefan Jun 24 '20 at 07:05
  • @NitinShinghal: You have two format specifies (`%d` and `%s`) in the string to the left of your `%`-operator and a one-element array as the right operand. Your problem can be more simple described as `%q(%d %s) % [222]`, which will also show the error. – user1934428 Jun 24 '20 at 09:48

1 Answers1

0

In your ruby_command variable, you have declared two positional arguments( %d and %s), whereas you only pass one value [current_process_id]. You need to pass the second value as well for %s.

Change your code to:

current_process_id = 222
ruby_command = %q(ps -x | awk '{if($5~"ruby" && $1!= %d ){printf("Killing ruby process: %s \n",$1);}};') % [current_process_id,current_process_id.to_s] 
puts ruby_command

Output:

ruby_command                                                                                                                                                                        
=> "ps -x | awk '{if($5~\"ruby\" && $1!= 222 ){printf(\"Killing ruby process: 222 \\n\",$1);}};'"

If you don't want to display the value, and you just want to display "%s", you can just escape it with %%:

ruby_command = %Q(ps -x | awk '{if($5~"ruby" && $1!= %d ){printf("Killing ruby process: %%s \n",$1);}};') % [current_process_id]

Output:

ruby_command                                                                                                                                                                        
=> "ps -x | awk '{if($5~\"ruby\" && $1!= 222 ){printf(\"Killing ruby process: %s \n\",$1);}};'"
CanciuCostin
  • 1,773
  • 1
  • 10
  • 25