Intro to Ruby - Blocks

Ruby

Overview

Blocks, procs, and lambas (a.k.a. closures) capture code that remember the context in which it was defined, using that same context each time it is executed. Blocks are used often in Ruby programming and are definitely worth mastering. Besides the books mentioned earlier, you can also read more about them here. The following is only a brief look at the basics.

Code

# Example methods, scroll down to read more about how these methods are being used.

def proc_return
p = Proc.new {return "I am here..."}
puts p.call
"...but not here."
end

def lambda_return
p = lambda { return "I am here..." }
puts p.call
"...and I am here too."
end

def implicit_block
puts "Enter."
yield
puts "Exit."
end

def explicit_block &block
puts "Enter."
block.call
puts "Exit."
end

# Here we have a standard block of code that prints words from the "words" array.
puts "01 Blocks with do...end\n\n"
words = %w{one two three four five}
words.each do |word|
puts "[#{word}] "
end

# Here is another block of code, same as above, but using a more condensed syntax for blocks.
# NOTE: {} syntax takes precidence over do...end syntax and is great for one-liners and keeping your code condensed.
puts "\n02 Blocks with {}\n\n"
words.each {|word| puts "[#{word}] "}

# The following demonstrates a proc being created and returning a message. New procs, when returning, will exit their
# enclosing scope. Notice how the last string is not returned.
puts "\n03 Proc Return\n\n"
puts proc_return

# The following demonstrates a lambda being created and returned. Notice how returning from the lambda does not
# exit the enclosing method.
puts "\n04 Lamda Return\n\n"
puts lambda_return

# Demonstrates an implicit block call. Pay attention to the block being passed in and the "yeild" statement
# within the method.
puts "\n05 Implicit Block\n\n"
implicit_block {puts "In block."}

# Demonstrates call to the block as passed in as a parameter (BTW, it becomes a proc when parameterized).
puts "\n06 Explicit Block\n\n"
explicit_block {puts "In block."}

Output

01 Blocks with do...end

[one]
[two]
[three]
[four]
[five]

02 Blocks with {}

[one]
[two]
[three]
[four]
[five]

03 Proc Return

I am here...

04 Lamda Return

I am here...
...and I am here too.

05 Implicit Block

Enter.
In block.
Exit.

06 Explicit Block

Enter.
In block.
Exit.

Download

The code above is provided as a Ruby script so that you can quickly execute all the examples above if you like. Just download, unzip, and type the following to execute all examples via the command line: ruby 08-blocks.rb.

What’s Next

Classes

Tags:

Friday, February 27th, 2009 Software

No comments yet.

Leave a comment

You must be logged in to post a comment.