Hello --

On Sat, 12 May 2001, Sunil Gangadharan wrote:

> Hi,
> I was looking at ruby regular expressions and noticed that the following
> commands all returned the same results:
>
> "string"['r']               --> "r"
> "string"[/r/]              --> "r"
> "string"[/[r]/]            --> "r"
>
>
> How does Ruby handle regular expressions? Does Ruby handle the
> expression exp as 'exp' or /exp/?
>
> This might be confusing especially since
> "st'r'ing"[' 'r' ']
> returns a parse error.
>
> Leads appreciated.

In your examples, the result is the same by coincidence.  The
underlying principle is slightly different in each case.

 "string"['r']               --> "r"

Here you've asked for the substring "r" (not a regular expression),
which is found.

 "string"[/r/]              --> "r"

Here you've asked for a substring matching the pattern /r/, which is
also found.

 "string"[/[r]/]            --> "r"

Here you've asked for a substring matching the pattern /[r]/ (that is,
one character from the character class whose members are "r").  It too
is found.

By way of contrast and/or clarification:

  irb 4> "string"["r."]      # substring
     ==>nil
  irb 5> "string"[/r./]      # regex: 'r' plus any char except newline
     ==>"ri"
  irb 6> "string"[/[r!@#]/]  # regex: match char class "r!@#"
     ==>"r"


David

-- 
David Alan Black
home: dblack / candle.superlink.net
work: blackdav / shu.edu
Web:  http://pirate.shu.edu/~blackdav