We Recommend

Beginning Ruby: From Novice to Professional Beginning Ruby: From Novice to Professional
Beginning Ruby is a thoroughly contemporary guide for every type of reader wanting to learn Ruby, from novice programmers to web developers to Ruby newcomers. It starts by explaining the principles behind object-oriented programming and within a few chapters builds toward creating a genuine Ruby application.


Posted By

cczona on 03/13/08


Tagged

regex ruby String


Versions (?)


Use regex to match a Ruby substring, and reference it like an index


Published in: Ruby 


URL: http://whytheluckystiff.net/articles/rubyOneEightOh.html

  1. # pass a Regexp into a String as if it were an Array index
  2.  
  3. "cat"[/c/]
  4. #=> "c"
  5. "cat"[/z/]
  6. #=> nil
  7.  
  8.  
  9. # pass in an optional second argument, to return the content of the nth matching group
  10.  
  11. re_phone = /(\d{3})-(\d{3})-(\d{4})/
  12. "986-235-1001"[re_phone, 2]
  13. #=> "235"

Report this snippet 

You need to login to post a comment.