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

Simulating Classes with Closures

If you think about it, classes are a way of packaging up data and behavior. Instances created of a class are distinct from each other. In other words, each instance has its own state. Closures also provide that functionality. Let’s see how with an example.

Say you want to build a very simple counter program. The counter program can do the following:

  • Get the current value of the counter.
  • Increment the counter.
  • Decrement the counter.

This is the essence of what most classes do: retrieve and modify data. Here’s one possible implementation of a Counter class:

 class​ Counter
 def​ initialize
  @x = 0
 end
 
 def​ get_x
  @x
 end
 
 def​ incr
  @x += 1
 end
 
 def​ decr ...

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