Close

Ruby – Passing a code block into a method using the “yield” keyword

$ cat testscript.rb
#!/usr/bin/env ruby

def normal_welcome
   puts "about to execute:"
   yield
   puts "finished executing"
end

normal_welcome do
    puts 1 + 1
    puts 2 + 2
    puts 3 + 3
    puts 4 + 4
end

The above outputs:

$ ./testscript.rb
about to execute:
2
4
6
8
finished executing