Pass Ruby Procs As Variables
Join the DZone community and get the full member experience.Join For Free
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)
Opinions expressed by DZone contributors are their own.