Created
March 5, 2014 00:17
-
-
Save hayeah/9358653 to your computer and use it in GitHub Desktop.
ruby method block and yield
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
| # In Ruby, you can always pass a block to a method call. | |
| def foo | |
| end | |
| # Call foo with a block, but foo just ignores the block | |
| foo { puts "doesn't call the block" } | |
| # foo can capture the block | |
| def foo(&block) | |
| # still doesn't do anything with the block | |
| end | |
| # foo can call the captured block | |
| def foo(&block) | |
| block.call | |
| end | |
| # yield is a more efficient way to do the same as above | |
| def foo | |
| yield | |
| end | |
| # the following two are equivalent | |
| def foo(&block) | |
| !block.nil? && block.call | |
| end | |
| def foo | |
| yield if block_given? | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment