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!
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.142.250.203