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

Block Pattern #3: Beautiful Object Initialization

There are a couple of ways to initialize an object in Ruby. Oftentimes, this is under the guise of applying configuration on an object. They usually mean the same thing. Here’s an example taken from the Twitter Ruby Gem:[4]

 client = Twitter::REST::Client.new ​do​ |config|
  config.consumer_key = ​"YOUR_CONSUMER_KEY"
  config.consumer_secret = ​"YOUR_CONSUMER_SECRET"
  config.access_token = ​"YOUR_ACCESS_TOKEN"
  config.access_token_secret = ​"YOUR_ACCESS_SECRET"
 end

See if you can guess at how this is implemented. Here’s a hint: consumer_key and the rest belong to accessors of Twitter::REST::Client. You’re going to build the bare minimum to get the preceding code to work. The code is ...

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