Functions and Blocks

Blocks in Ruby

A block contains code that can be executed.


Syntax
#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
end

Notes

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.


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

Add to Slack

< Functions   |   Collect >

© 2018 SyntaxDB. All Rights Reserved.