Closures- Ruby

October 10, 2010 § Leave a comment

I am learning Ruby for a project. Ruby utilizes closures extensively and the implementation within ruby for closures is elegant. So what is Closure: Well it is like an anonymous function that has a closed scope, meaning it has access to local variables.
You will see closures being used everywhere in Ruby. Below is a very common example if you are doing Ruby on Rails

respond_to do |format|
format.html # show.html.erb
format.xml  { render : xml => @order }

It is very easy to tell what the code is doing. Depending on the request the code block either execute the first closure to display html or executes the other closure to display xml. This type of closure i think takes advantage of the yield keyword. The yield keyword tells the function to execute the closure.

Below is an example where I use yield:

def closure_example
first =  "This comes first"
second = "This comes second"
puts first
yield(first, second)
puts second
my_first = ""
my_second = ""
closure_example do |first, second|
puts "This is the middle. "
my_first = first
my_second = second
puts "value of first: '#{my_first}'"
puts "value of second: '#{my_second}'"

The above code will results in the output:

This comes first
This is the middle.
This comes second
value of first: 'This comes first'
value of second: 'This comes second'

Another simple example:

10.times {puts "display me."}

times is a method on 10 that executes the code in the closure(puts “display me.”) 10 times.

Final example

['ruby', 'is', 'cool'].collect {|item| item.upcase}

This line of code takes each element of an array, calls the closure on it, and then builds a collection with the results.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

What’s this?

You are currently reading Closures- Ruby at There is something called standard work, but.


%d bloggers like this: