Skip to content

Instantly share code, notes, and snippets.

@havenwood
Created December 4, 2020 03:52
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 havenwood/7f6456e01c18a01776fb83d4fd561209 to your computer and use it in GitHub Desktop.
Save havenwood/7f6456e01c18a01776fb83d4fd561209 to your computer and use it in GitHub Desktop.
Examples to illustrate what `yield` does in Ruby
##
# 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