Skip to content

Instantly share code, notes, and snippets.

@arches
Last active February 17, 2016 17:56
Show Gist options
  • Save arches/9095593 to your computer and use it in GitHub Desktop.
Save arches/9095593 to your computer and use it in GitHub Desktop.
Syntactic sugar for simple filtering. A halfway point between posts.select(&:published) and posts.select{|post| post.comments.any?}
# before - each object in the enumerable is passed to the block
posts.select { |post| post.comments.any? }
class Array
def select(&blk)
if blk.arity == 0
super { |obj| obj.instance_exec &blk }
else
super
end
end
end
# after - block is optionally evaluated in the context of each object in the enumerable
posts.select { |post| post.comments.any? }
posts.select { comments.any? }
# basically the same setup with a different method name for different use case
class Object
def do(&blk)
instance_exec &blk
end
end
# before - reference the object
foo.bar * foo.baz
# after
foo.do { bar*baz }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment