Over a million developers have joined DZone.

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)
Topics:

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}