Skip to content

Instantly share code, notes, and snippets.

@tranghaviet
Last active July 22, 2017 11:25
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 tranghaviet/3cafe5a41507fb41dfbd6afc3ab0711d to your computer and use it in GitHub Desktop.
Save tranghaviet/3cafe5a41507fb41dfbd6afc3ab0711d to your computer and use it in GitHub Desktop.
Yield in ruby
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