Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 492
ToTenMilan Avatar asked Jan 22 '17 14:01

ToTenMilan


1 Answers

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
like image 128
mrlew Avatar answered Oct 12 '22 14:10

mrlew