Procs and Lambdas

In the examples up to now, blocks have been used in cahoots with methods. This has been a requirement since nameless blocks cannot have an independent existence in Ruby. You cannot, for example, create a stand-alone block like this:

{|x| x = x*10; puts(x)}        # This is not allowed!

This is one of the exceptions to the rule that “everything in Ruby is an object.” A block clearly is not an object. Every object is created from a class, and you can find an object’s class by calling its class method.

Do this with a hash, for example, and the class name “Hash” will be displayed:

puts({1=>2}.class)

Try this with a block, however, and you will only get an error message:

puts({|i| puts(i)}.class) #<= error!

Get The Book of Ruby now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.