Posted By

cczona on 03/13/08


Tagged

regex ruby String


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

webstic


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.