2014-11-03 22 views
0

我下面对红宝石的正则表达式的教程工作,但似乎不工作方法match1.regex似乎不是红宝石

Tutorial 

re = /(\w*)\s(\w*),\s?([\w\s]*)/ 
match1 = str1.match re 
match2 = str2.match re 
match1.regex # => wsw,s[ws]  (this is IRB's unique way of showing regular expressions; it will still work normally) 

My console 

The regex method the method throws an error 

1.9.3-p547 :033 > re = /(\w*)\s(\w*),\s?([\w\s]*)/ 
=> /(\w*)\s(\w*),\s?([\w\s]*)/ 
1.9.3-p547 :034 >  match1 = str1.match re 
=> #<MatchData "Joe Schmo, Plumber" 1:"Joe" 2:"Schmo" 3:"Plumber"> 
1.9.3-p547 :035 >  match2 = str2.match re 
=> #<MatchData "Stephen Harper, Prime Minister" 1:"Stephen" 2:"Harper" 3:"Prime Minister"> 
1.9.3-p547 :036 > match1.regex 
NoMethodError: undefined method `regex' for #<MatchData "Joe Schmo, Plumber" 1:"Joe" 2:"Schmo" 3:"Plumber"> 
    from (irb):36 
    from /home/fernando/.rvm/rubies/ruby-1.9.3-p547/bin/irb:12:in `<main>' 
1.9.3-p547 :037 > 
+0

让我们来完成解决问题的步骤。错误消息说类'match1.class => MatchData'没有实例方法'regex'。该类列表实例方法的* [docs](http://www.ruby-doc.org/core-2.1.3/MatchData.html)*('#==', '#[]',' #begin','#captures'等等)。没有'regex'方法,但有一个'regexp'方法,所以你似乎拼错了方法名。另外:在你的答案中包含'str1'和'str2'会有帮助,因此读者可以重现你的结果。 – 2014-11-03 17:17:32

回答

0

的方法称为正则表达式,我认为它应该是

match1.regexp 

最后'p'

+0

match1.regexp => /(\ w *)\ s(\ w *),\ s?([\ w \ s] *)/ – user3678471 2014-11-03 15:45:50

+0

响应类似 – user3678471 2014-11-03 15:46:46

+0

这是一个链接http://代码。 tutsplus.com/tutorials/ruby-for-newbies-regular-expressions--net-19812 – user3678471 2014-11-03 15:47:04