Created
December 4, 2020 03:52
-
-
Save havenwood/7f6456e01c18a01776fb83d4fd561209 to your computer and use it in GitHub Desktop.
Examples to illustrate what `yield` does in Ruby
This file contains 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
## | |
# Examples without block arguments | |
def example_without_block(function) | |
function.call + 'ay' | |
end | |
example_without_block ->{ 'ok' } | |
#=> "okay" | |
def example_explicit_block(&block) | |
block.call + 'ay' | |
end | |
example_explicit_block { 'ok' } | |
#=> "okay" | |
def example_yield_block | |
yield + 'ay' | |
end | |
example_yield_block { 'ok' } | |
#=> "okay" | |
## | |
# Examples with one block argument | |
def example_without_block(function) | |
function.call('ay') | |
end | |
example_without_block proc { |ending| 'ok' + ending } | |
#=> "okay" | |
def example_explicit_block(&block) | |
block.call('ay') | |
end | |
example_explicit_block { |ending| 'ok' + ending } | |
#=> "okay" | |
def example_yield_block | |
yield('ay') | |
end | |
example_yield_block { |ending| 'ok' + ending } | |
#=> "okay" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment