Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between scan and match on Ruby string

Tags:

regex

ruby

I am new to Ruby and has always used String.scan to search for the first occurrence of a number. It is kind of strange that the returned value is in nested array, but I just go [0][0] for the values I want. (I am sure it has its purpose, just that I haven't used it yet.)

I just found out that there is a String.match method. And it seems to be more convenient because the returned array is not nested.

Here is an example of the two, first is scan:

>> 'a 1-night stay'.scan(/(a )?(\d*)[- ]night/i).to_a => [["a ", "1"]] 

then is match

>> 'a 1-night stay'.match(/(a )?(\d*)[- ]night/i).to_a => ["a 1-night", "a ", "1"] 

I have check the API, but I can't really differentiate the difference, as both referred to 'match the pattern'.

This question is, for simply out curiousity, about what scan can do that match can't, and vise versa. Any specific scenario that only one can accomplish? Is match the inferior of scan?

like image 893
lulalala Avatar asked Nov 03 '11 10:11

lulalala


People also ask

What does match do in Ruby?

Ruby | Regexp match() function Regexp#match() : force_encoding?() is a Regexp class method which matches the regular expression with the string and specifies the position in the string to begin the search.

How do you match a string in Ruby?

=~ is Ruby's basic pattern-matching operator. When one operand is a regular expression and the other is a string then the regular expression is used as a pattern to match against the string. (This operator is equivalently defined by Regexp and String so the order of String and Regexp do not matter.

What is regex in Ruby?

Advertisements. A regular expression is a special sequence of characters that helps you match or find other strings or sets of strings using a specialized syntax held in a pattern.


1 Answers

Short answer: scan will return all matches. This doesn't make it superior, because if you only want the first match, str.match[2] reads much nicer than str.scan[0][1].

ruby-1.9.2-p290 :002 > 'a 1-night stay, a 2-night stay'.scan(/(a )?(\d*)[- ]night/i).to_a  => [["a ", "1"], ["a ", "2"]]  ruby-1.9.2-p290 :004 > 'a 1-night stay, a 2-night stay'.match(/(a )?(\d*)[- ]night/i).to_a  => ["a 1-night", "a ", "1"]  
like image 146
Jonathan Julian Avatar answered Oct 17 '22 05:10

Jonathan Julian