Last active
February 17, 2016 17:56
-
-
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?}
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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? } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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