Skip to content

Instantly share code, notes, and snippets.

@maraigue
Created January 12, 2012 07:06
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 maraigue/1599144 to your computer and use it in GitHub Desktop.
Save maraigue/1599144 to your computer and use it in GitHub Desktop.
[Ruby] Enumerable#grepの補集合
require "./vgrep.rb"
p ["foo", "bar", "buz"].grep(/b/) # => ["bar", "buz"]
p ["foo", "bar", "buz"].vgrep(/b/) # => ["foo"]
p ["foo", "bar", "buz"].vgrep(/b/){ |x| x.upcase } # => ["FOO"]
module Enumerable
def vgrep(cond, &block) # 名前は "grep -v" より
result = select{ |x| !(cond === x) } # Ruby1.8.7以降ならtapで書くところなんだけど
result.map!(&block) if block
result
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment