[#3006] mismatched quotation — "stevan apter" <apter@...>

ruby documentation uses a punctuation convention i've never seen

13 messages 2000/05/27

[ruby-talk:02898] Re: Funny unexpected match....

From: Dave Thomas <Dave@...>
Date: 2000-05-18 19:55:54 UTC
List: ruby-talk #2898
The following message is a courtesy copy of an article
that has been posted to comp.lang.ruby as well.

"David Douthitt" <DDouthitt@cuna.com> writes:

> Put simply, using "||" as a match expression in gsub matches an
> empty line.  Say WHAT?  I want to match a literal "vertical-bar
> vertical-bar".

You're getting lulled into a false sense of string escaping.

test = "||"          # test = "||"
test2 = "\|\|"       # test2 also equals "||"
line = ""

 p line.gsub(/#{test}/, "*** ding ding ding ***")
 p line.gsub(/#{test2}/, "*** dong dong dong ***")

So both lines are the same - they use unescaped '|'s

Generic ways to solve the problem if you want to match a literal in a 
string include:

  1. Use  test2 = Regexp.escape("||")

  2. If you're literally just looking for a substring, then

       line["||"]

     will return "||" or nil

> PS: This code came up in a pretty printer I'm writing - not a
> "reformatter" but an HTML-based "pretty-printer" which highlights
> different sections and so on.  If you've read "Code Complete" you've
> seen something like it.  If you haven't read "Code Complete", YOU
> SHOULD (as well as any programmers working for you, or any
> programmers you work for, or any programmers you know...... :-)

After reading Pragmatic Programmer, of course...  ;-)


Dave

In This Thread

Prev Next