生成包含转义插值的字符串

时间:2014-02-14 08:51:52

标签: ruby

我有一个字符串:

<ul>
  <li><a href="/<%= @home %>/">welcome</a></li>
</ul>

我正在使用Nokogiri获取其所有href标记的a属性并构建一个哈希数组。我期待着:

[{
  :href => "/#{ @home }/",
  :title => "welcome"
}]

我试过这个剧本:

doc = Nokogiri::HTML(open(file))
menu = []

doc.css('a').each do |item|
  menu.push({
    :href => item[:href].gsub(/<%=(.*)%-?>/, "\#{\\1}"),
    :title => item.text
  })
end

生成的字符串会自动转义;注意哈希符号之前的额外反斜杠:

[{
  :href => "/\#{ @home }/",
  :title => "welcome"
}]

我无法弄清楚原因。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

字符串中没有'\'inspect添加了puts:如果您asd = '<%= asd %>'.gsub(/<%=(.*)%-?>/, "\#{\\1}") #=> "\#{ asd }" p asd #=> "\#{ asd }" <- this is `asd.inspect`, which is returned by `p` "\#{ asd }" <- this is `asd.inspect`, which is printed by `p` puts asd #=> nil <- this is `nil`, which is returned by `puts` #{ asd } <- this is `asd.to_s`, and it is the actual string 字符串,您就会意识到:

{{1}}