Ruby Procs
Blocks are not objects, but they can be converted into objects of class Proc. This can be done by calling the lambda method of the class Object. A block created with lambda acts like a Ruby method. If you don't specify the right number of arguments, you can't call the block.
prc = lambda {"hello"} Proc objects are blocks of code that have been bound to a set of local variables. The class Proc has a method call that invokes the block. The program p024proccall.rb illustrates this.
# Blocks are not objects
# they can be converted into objects of class Proc by calling lambda method
prc = lambda {puts 'Hello'}
# method call invokes the block
prc.call
# another example
toast = lambda do
'Cheers'
end
puts toast.call The output is:
>ruby p024proccall.rb
Hello
Cheers
>Exit code: 0 Remember you cannot pass methods into other methods (but you can pass procs into methods), and methods cannot return other methods (but they can return procs).
The next example shows how methods can take procs. Example p025mtdproc.rb
=begin
You cannot pass methods into other methods (but you can pass procs into methods),
and methods cannot return other methods (but they can return procs)
=end
def some_mtd some_proc
puts 'Start of mtd'
some_proc.call
puts 'End of mtd'
end
say = lambda do
puts 'Hello'
end
some_mtd say The output is:
>ruby p025mtdproc.rb
Start of mtd
Hello
End of mtd
>Exit code: 0 Here's another example of passing arguments using lambda.
a_Block = lambda { |x| "Hello #{x}!" }
puts a_Block.call 'World'
# output is: Hello World! Fabio Akita a Brazilian Rails enthusiast, also known online as "AkitaOnRails", wrote this exclusive article on Ruby Blocks/Closures for the rubylearning.github.io members like you. Do read, after you have gone through this lesson.
Note: The Ruby Logo is Copyright (c) 2006, Yukihiro Matsumoto. I have made extensive references to information, related to Ruby, available in the public domain (wikis and the blogs, articles of various Ruby Gurus), my acknowledgment and thanks to all of them. Much of the material on rubylearning.com and in the course at rubylearning.org is drawn primarily from the Programming Ruby book, available from The Pragmatic Bookshelf.