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

Test Your Understanding!

  1. Reimplement Symbol#to_proc. Now that you’ve seen how Symbol#to_proc is implemented, you should have a go at it yourself.

  2. You can use #to_proc instantiate classes. . Consider this behavior:

     class​ SpiceGirl
     def​ initialize(name, nick)
      @name = name
      @nick = nick
     end
     
     def​ inspect
     "​​#{​@name​}​​ (​​#{​@nick​}​​ Spice)"
     end
     end
     
     spice_girls = [[​"Mel B"​, ​"Scary"​], [​"Mel C"​, ​"Sporty"​],
     [​"Emma B"​, ​"Baby"​], [​"Geri H"​, ​"Ginger"​,], [​"Vic B"​, ​"Posh"​]]
     
     p spice_girls.map(&SpiceGirl)

    This returns:

     [Mel B (Scary Spice), Mel C (Sporty Spice),
      Emma B (Baby Spice), Geri H (Ginger Spice), Vic B (Posh Spice)]

    This example demonstrates how to_proc can be used to initialize a class. ...

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