DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world
Pass Ruby Procs As Variables
Procs are closure objects. They can be assigned to variables and passed as parameters.
class Array def iterate!(code) self.each_with_index do |n, i| self[i] = code.call(n) end end end the_array = [1, 2, 3, 4, 5, 6] square = Proc.new do |n| n ** 2 end cubic = Proc.new do |n| n ** 3 end the_array.iterate!(square)
Reference: http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/ (Tutorial post on blocks, procs, lambdas and methods)