O'Reilly logo

Mastering Ruby Closures by Benjamin Tan Wei Hao

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 3

  1. The answer is exactly the one covered in the chapter:

     class​ Symbol
     def​ to_proc
      proc { |obj, args| obj.send(self, *args) }
     end
     end
  2. Since we’re interested in adding behavior to object initialization, it therefore makes sense to implement to_proc within the Class class. Here’s a possible implementation:

     class​ Class
     def​ to_proc
      proc { |args| ​new​(*args) }
     end
     end

    Since we’re creating objects with arrays, each array element is treated as a single object. Therefore, the proc takes a single argument.

    Next, we use the splat operator to convert the array into method arguments, and pass it into new, which then calls the initializer.

  3. The Proc#lambda? method.

  4. Both come from the Proc class.

  5. join_2. Lambdas ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required