Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
233 views
in Technique[技术] by (71.8m points)

ruby - Generate string containing escaped interpolation

I have a string:

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

I'm using Nokogiri to grab the href properties of all its a tags and build an array of hashes. I am expecting:

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

I tried this script:

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

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

The resulting string is automatically escaped; notice the extra backslash before the hash sign:

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

I can't figure out why. Any ideas?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You have not the '' in the string, it is added by the inspect: if you puts the string you will realize it:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...