Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...