Functions and Blocks

Blocks in Ruby

A block contains code that can be executed.

#x is a local variable which represents a parameter passed into a block
#one way to write a block
{ |x|
    #code to be executed

#other way to do it
do |x|
    #code to be executed


Blocks are not objects, but there are methods that can be used on blocks for repetition and local variable purposes.

The for-each loop is actually a block.

10.times { puts "This code will execute 10 times!" }

Add to Slack

< Functions   |   Collect >

© 2019 SyntaxDB. All Rights Reserved.