Search code examples
rubystringformatstring-formatting

Format string in ruby


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.


Solution

  • 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);}};'"