如何在Ruby字符串中输出反斜杠和双引号?

时间:2014-10-08 16:48:09

标签: ruby string

我试图输出

[fish] \"aquatic animal\"\n

但我最接近的是:

[fish]\aquatic animal

@entries.each do |key,value|
  puts "["+key+"]" +"\\"+value+"\n"
end

@entries = {"zebra"=>"African land animal with stripes", "fish"=>"aquatic animal", "apple"=>"fruit"}

2 个答案:

答案 0 :(得分:2)

TL; DR

使用Ruby的sprintf及其便捷的合作伙伴%,您可以让它变得非常简短易读:

@entries = {"zebra"=>"African land animal with stripes", "fish"=>"aquatic animal", "apple"=>"fruit"}

template = '[%s] \"%s\"\n'

@entries.each do |key_and_value|
  puts template % key_and_value
end
# => [zebra] \"African land animal with stripes\"\n
#    [fish] \"aquatic animal\"\n
#    [apple] \"fruit\"\n

你需要知道的是,在双引号内,反斜杠具有特殊含义。例如,在"foo\nbar"中,\n会转换为换行符:

puts "foo\nbar"
# => foo
#    bar

为了在双引号内使用文字反斜杠,它必须以反斜杠开头,它会“逃避”它:

puts "foo\\nbar"
# => foo\nbar

要在双引号内使用双引号,您需要以相同的方式转义它们:

puts "I have "inner" quotes"
# => SyntaxError: unexpected tIDENTIFIER, expecting end-of-input
#    puts "I have "inner" quotes"
#                       ^

puts "I have \"inner\" quotes"
# => I have "inner" quotes

如果我们想要打印[fish] \"aquatic animal\"\n,我们必须这样做:

puts "[fish] \\\"aquatic animal\\\"\\n"
# => [fish] \"aquatic animal\"\n

我们将每个\替换为\\,将每个"替换为\",这看起来非常混乱。有用的事情是使用Ruby的替代“百分号”语法:

puts %{[fish] \\"aquatic animal\\"\\n}
# => [fish] \"aquatic animal\"\n

我们仍然需要将\替换为\\,因为反斜杠仍然需要使用此语法进行转义,但双引号不需要转义,因此它更好一些。把它放在一起,我们得到了这个:

puts %{[#{key}] \\"#{value}\\"\\n}

这还不错,但它仍然不是特别容易阅读。另一种选择是使用sprintf,它允许我们定义“模板”字符串,然后在以后将值替换为它。由于我们不需要插值(#{...}),我们可以使用单引号,这意味着我们可以在其中使用反斜杠双引号而不转义它们:

template = '[%s] \"%s\"\n'
str = sprintf(template, "fish", "aquatic animal")
puts str
# => [fish] \"aquatic animal\"\n

如您所见,“模板”中的每个%s都被sprintf的一个参数替换。 Ruby还有sprintf的特殊快捷方式,即%运算符:

str = template % [ "fish", "aquatic animal" ]
puts str
# => [fish] \"aquatic animal\"\n

我们可以将它与您的循环结合起来,以获得特别干净的解决方案:

@entries = {"zebra"=>"African land animal with stripes", "fish"=>"aquatic animal", "apple"=>"fruit"}

template = '[%s] \"%s\"\n'
@entries.each do |key_and_value|
  puts template % key_and_value
end
# => [zebra] \"African land animal with stripes\"\n
#    [fish] \"aquatic animal\"\n
#    [apple] \"fruit\"\n

答案 1 :(得分:0)

尝试

puts "["+key+"]" +" "+ "\\\""+value+"\\\"\\n"