Skip to content

Instantly share code, notes, and snippets.

@sk187
Created March 31, 2015 15:59
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 sk187/cf8f83e10c389d1c384c to your computer and use it in GitHub Desktop.
Save sk187/cf8f83e10c389d1c384c to your computer and use it in GitHub Desktop.
Ruby Yield
# 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