Skip to content

Instantly share code, notes, and snippets.

@jonaphin
Created June 29, 2011 01:57
Show Gist options
  • Select an option

  • Save jonaphin/1052744 to your computer and use it in GitHub Desktop.

Select an option

Save jonaphin/1052744 to your computer and use it in GitHub Desktop.
Regexp#to_proc
### Jonathan Lancar - https://github.com/jonaphin ###
## Match Regular Expression to one or multiple strings
class Regexp
def to_proc
proc { |arg| arg.to_s[self] }
end
end
## USE CASE ##
params = ["Imagination", "is", "more", "important", "than", "knowledge."]
params2 = %w|Quote by Albert Einstein|
p params.map &/or/
# => [nil, nil, "or", "or", nil, nil]
p params.select &/o|r/
# => ["Imagination", "more", "important", "knowledge."]
p params2.select &/[or]/
# => ["Quote", "Albert"]
## Reasoning ##
# This simple implementation makes matching agains an array of strings effortless
# From Symbol#to_proc, a developer can easily guess what Regexp#to_proc might do
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment