Never been to DZone Snippets before?

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

Create a Proc in Ruby (See related posts)

Source: Robert Sosinski » Understanding Ruby Blocks, Procs and Lambdas [robertsosinski.com]

# example-5.rb
 
class Array
  def iterate!(code)
    self.each_with_index do |n, i|
      self[i] = code.call(n)
    end
  end
end
 
array_1 = [1, 2, 3, 4]
array_2 = [2, 3, 4, 5]
 
square = Proc.new do |n|
  n ** 2
end
 
array_1.iterate!(square)
array_2.iterate!(square)
 
puts array_1.inspect
puts array_2.inspect
 
# => [1, 4, 9, 16]
# => [4, 9, 16, 25]


This code is similar to creating a block in Ruby [dzone.com] however a proc is a type of re-usable block of code whereas a basic block of code is hard-wired to the object.

You need to create an account or log in to post comments to this site.


Click here to browse all 6646 code snippets

Related Posts