【问题标题】:Format string in rubyruby 中的格式化字符串
【发布时间】:2020-06-24 15:03:31
【问题描述】:

我有一个字符串和一个变量,我想在这个字符串中使用这个变量,所以它会在将它转换为字符串之前取那个值:

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

我试过了:

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

但这会报错:

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

我试过了:

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

这对我来说很好。但是我这样做的方式并不干净。

我正在寻找更清洁的方法。

【问题讨论】:

  • 你似乎在问same question again and again :-) 我知道这些是不同的方面,但也许你应该花点时间询问/整体解释问题?
  • @NitinShinghal:您在% 运算符左侧的字符串中有两种格式指定(%d%s),以及一个单元素数组作为右操作数。您的问题可以更简单地描述为%q(%d %s) % [222],它也会显示错误。

标签: ruby string format string-formatting


【解决方案1】:

在您的 ruby_command 变量中,您声明了两个位置参数(%d%s),而您只传递了一个值 [current_process_id]。您还需要为 %s 传递第二个值。

将您的代码更改为:

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

输出:

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

如果您不想显示该值,而只想显示 "%s",则可以使用 %% 对其进行转义: p>

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

输出:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-15
    • 1970-01-01
    • 2010-10-22
    • 1970-01-01
    相关资源
    最近更新 更多