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:

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

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

{{ parent.tldr }}

{{ parent.urlSource.name }}