Every month, the Kansas City Ruby User group meets to discuss current events in the development world, and learn from each other. This month, Shashank Date will be offering a refresher of his talk from last year on Procs and lambdas. Often, Ruby on Rails developers can be strong on Rails, and light on Ruby.
This talk covers one of the most powerful Ruby features that is used all the time by the Rails framework itself. Newer developers, however, may not realize just how easy it is to harness the power of blocks, and by extension Proc and lambda calls, in methods. I might also stand up and give a brief rundown on binding
, a closely related concept.
The Where and When
If you live in the Kansas City area, join us Tuesday January 11, 2010 at 6:30pm here:
Centriq Foss
8700 State Line Road
Leawood, KS 66206
Visit the meetup page for more info.
Preview
To give some background, here’s a code snippet that illustrates a block:
def do_for_each(array=[], &block) array.each{|element| block.call element} end do_for_each([1,2,3]){|x| puts x}
A Ruby block is a chunk of code that can be passed to a method and run at will. This code prints each element of the array on its own line. If this looks familiar, that’s because it’s really a lamer version of the Array
class’ map
instance method.
When you pass a block to a method like this, you’re recreating a Proc object implicitly. You don’t have to do anything extra, and Ruby knows what to do with this extra code hanging off the method call. But what if, for instance, you needed to pass *two* blocks into a method? Here’s one way:
def custom_print(words, quiet, loud) words.each do |word| if word =~ /!$/ puts loud.call(word) else puts quiet.call(word) end end end words = ['hello', 'world!', 'turkey'] custom_print(words, lambda{|w| w + '.'}, lambda{|w| w.upcase})
In this example, words are “loud” if they end in an exclamation point. I chose to end quiet words with a period, and to capitalize loud words. Please join us Tuesday for a much more detailed explanation.
Tags: blocks, Business, kansas city, lambda, Proc, Rails, Ruby, yield
Leave a Reply