Skip to content

Instantly share code, notes, and snippets.

@nevans
Forked from pjb3/gist:50340
Created January 23, 2009 16:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nevans/51068 to your computer and use it in GitHub Desktop.
Save nevans/51068 to your computer and use it in GitHub Desktop.
# I didn't like the original for two reasons:
# 1) joining strings into a regex with "|" smells like a future bug to me
# (unless you will never match on anything containing '|')
# 2) always using regex smells to me. why not leave that decision to the
# user of this method? I offer two alternatives, based on === and ==.
# 3) this might be premature optimization, but I've skipped the map step
# to save memory and time in calling methods that may not be used.
# true if any fields of this object match any of the values
# (implicitly converting values to case insensitive Regexp, as in original)
def any_field_matches_any_value_by_regex?(fields, values)
regexes = values.map {|v| Regexp.new(v, Regexp::IGNORECASE) }
fields.any? {|f| val = send(f); regexes.any? {|re| val =~ re } }
end
# true if any fields of this object match any of the values
# (using ===, my preferred approach. works with regexp, string, class, etc)
def any_field_matches_any_value?(fields, values)
fields.any? {|f| val = send(f); values.any? {|v| v === val } }
end
# true if any fields of this object matches any of the values
# (using include?, which generally uses ==)
def any_field_included_in_values?(fields, values)
fields.any? {|f| values.include? send(f) }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment