Created
April 30, 2020 23:21
-
-
Save muneebaahmad/92f1ce0e3e7b82a2d421f5a614bc66ca to your computer and use it in GitHub Desktop.
An example to understand the yield keyword 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 greeting | |
puts '2' | |
yield | |
end | |
puts '1' | |
greeting { puts '3'} | |
=> 1 | |
=> 2 | |
=> 3 | |
# -------------------------------------------------------- # | |
def welcome(input) | |
puts '2' | |
puts "#{input}" | |
yield | |
end | |
puts '1' | |
welcome(3) { puts '4' } | |
=> 1 | |
=> 2 | |
=> 3 | |
=> 4 | |
# -------------------------------------------------------- # | |
def welcome(input) | |
puts '2' | |
puts "#{input}" | |
yield(input) | |
end | |
puts '1' | |
welcome(3) { |x| puts "#{x} * 2 is #{x*2}" } | |
=> 1 | |
=> 2 | |
=> 3 | |
=> 3 * 2 is 6 | |
# -------------------------------------------------------- # |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment