Functions and Blocks

Yield in Ruby

A yield statement is used inside a method to call a block.


Syntax
def yield_method
    #method code
    #will execute block code here
    yield passed_parameter
    #other method code
end

yield_method {  |passed_parameter|  #block code    }

   

Notes

Once the block has finished executing, it will return to the method.


Example
def print_name
    name = gets.chomp
    yield name
    last_name = gets.chomp
    puts "Full name: #{name} #{last_name}"
end

print_name { |name| puts "Hello, #{name}! }

# would output: "Hello, #{name}" followed by "Full name: #{name} #{last_name}"
    

Add to Slack

< Collect   |   Proc >

© 2018 SyntaxDB. All Rights Reserved.