Skip to content

Instantly share code, notes, and snippets.

@muneebaahmad
Created April 30, 2020 23:21
Show Gist options
  • Save muneebaahmad/92f1ce0e3e7b82a2d421f5a614bc66ca to your computer and use it in GitHub Desktop.
Save muneebaahmad/92f1ce0e3e7b82a2d421f5a614bc66ca to your computer and use it in GitHub Desktop.
An example to understand the yield keyword in ruby.
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