Created
March 31, 2015 15:59
-
-
Save sk187/cf8f83e10c389d1c384c to your computer and use it in GitHub Desktop.
Ruby Yield
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
# Yield in Ruby allow you to pass a block implicitly which not only makes it faster | |
# to type out this pattern but it also faster to execute! | |
# Regular Block Syntax | |
def calculate(a, b, action) | |
action.call(a,b) | |
end | |
# Defining the lambda add and subtract | |
add = lambda {|a,b| a+b} | |
subtract = lambda {|a,b| a-b} | |
puts calculate(10,5, add) | |
puts calculate(10,5, subtract) | |
# Returns | |
"15" | |
"5" | |
#Yield Syntax | |
def calculate(a, b) | |
yield(a,b) | |
end | |
puts calculate(10,5){|a,b| a+b} #Add | |
puts calculate(10,5){|a,b| a-b} #Subtract | |
# Returns | |
"15" | |
"5" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment