Skip to content

Instantly share code, notes, and snippets.

@hayeah
Created March 5, 2014 00:17
Show Gist options
  • Save hayeah/9358653 to your computer and use it in GitHub Desktop.
Save hayeah/9358653 to your computer and use it in GitHub Desktop.
ruby method block and yield
# 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