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


/ Published in: Ruby
Save to your folder(s)



Copy this code and paste it in your 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"

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

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.