NoMethodError: undefined method `match?' for "Ruby":String
Asked Answered
H

1

9

I'm trying to check whether input from user matches RegEx [a-zA-z] so I've checked the docs for proper method. I found match? in Ruby-doc.org and copied the example shown in docs to irb, but instead of true I'm getting this:

2.3.3 :001 > "Ruby".match?(/R.../) 
NoMethodError: undefined method `match?' for "Ruby":String
Did you mean?  match
        from (irb):1
        from /usr/local/rvm/rubies/ruby-2.3.3/bin/irb:11:in `<main>'

Why this method doesn't work in my irb?

Holarctic answered 22/1, 2017 at 14:50 Comment(2)
I notice you are using 2.3.3 and the doc is for 2.4.0. That may be relevant.Mariandi
Yes, that is the case. ThanksHolarctic
P
20

String#match? and Regexp#match? are Ruby 2.4 new methods. Check here and here.

This new syntax is not only an alias. It's faster than other methods mainly because it doesn't update the $~ global object. According to this benchmark, it runs up to three times faster than other methods.

BTW, in order to achieve your goal (check whether a string matches a regex), you might [1] update your ruby version to use this new feature or [2] use another approach.

For instance, you can use the =~ operator, that returns nil if not found, or the position where the matchs starts. Can be used like that:

if "Ruby" =~ /R.../
   puts "found"
end
Plaided answered 22/1, 2017 at 14:58 Comment(3)
There was a syntax error. I took the liberty to edit it.Mcgrew
@EricDuminil Sure, I didn't notice. Thanks!Plaided
I can confirm that upgrading my Ruby version from 2.3.3 to 2.4.0 solved this problem for me.Delilahdelimit

© 2022 - 2024 — McMap. All rights reserved.