Forum: Ruby Regexp ops: get rid of !=~?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Gary Y. (Guest)
on 2009-02-10 19:31
(Received via mailing list)
The proper way to see if something doesn't match is
"foo" !~ /bar/

The ~/blah/ operator exists to apply to $_

Unfortunately this means that

"foo" !=~ /bar/

does

"foo".!= (~bar), which doesn't produce an error, even though it's
basically
garbage.
Instead it fails silently by returning true (nil or an number are not
strings).

Is there a way w/ Ruby to define a mega !=~ operator and either have it
do
!~ or have it throw an exception?
Or an easy way w/ Ruby to have the parser warn about it?

Alas google is not good for searching for !=~, so apologies if this has
been
previously discussed.

Thanks,
Gary
Brian C. (Guest)
on 2009-02-11 16:59
Gary Y. wrote:
> "foo" !=~ /bar/
>
> does
>
> "foo".!= (~bar)

Actually: "foo" != ~/bar/

> which doesn't produce an error, even though it's
> basically
> garbage.
> Instead it fails silently by returning true (nil or an number are not
> strings).

The problem here is ~/bar/

This is an ugly Perlism in Ruby which hardly anybody ever uses anyway.
Search for Regexp#~ in ri.

Personally, I would be very happy to lose this entirely, together with
all the other implicit tests and side-effects on $_ (such as is done by
Kernel#gets and IO#gets). Or at least have a flag to turn on this
behaviour.

Regards,

Brian.
Brian C. (Guest)
on 2009-02-11 17:02
Gary Y. wrote:
> Or an easy way w/ Ruby to have the parser warn about it?

irb(main):001:0> Regexp.class_eval{undef_method :~}
=> Regexp
irb(main):002:0> ~/foo/
NoMethodError: undefined method `~' for /foo/:Regexp
  from (irb):2
This topic is locked and can not be replied to.