Last active
July 22, 2017 11:25
-
-
Save tranghaviet/3cafe5a41507fb41dfbd6afc3ab0711d to your computer and use it in GitHub Desktop.
Yield 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
def calculation(a, b, operation) | |
operation.call(a, b) | |
end | |
puts calculation(5, 6, lambda { |a, b| a + b }) # addition | |
# OR puts calculation(5, 6, ->(a, b) { a + b }) | |
# OR puts calculation(5, 6, Proc.new{ |a, b| a + b }) | |
# OR puts calculation(5, 6, proc{ |a, b| a + b }) | |
puts calculation(5, 6, lambda { |a, b| a - b }) # subtraction | |
def calculation2(a, b) | |
yield(a, b) # Pass parameters to block | |
end | |
# Pass a block when using yeild | |
puts calculation2(5, 6) { |a, b| a + b } # addition | |
puts calculation2(5, 6) { |a, b| a - b } # subtraction | |
# prevent exception raised when using yield | |
def foo | |
yield if block_given? | |
end | |
# REMEMBER: yeild gives us better perfomance |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment