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

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"] 

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)