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

Separating the General from the Specific

The ability to encapsulate behavior into blocks and pass it into methods is an extremely useful programming technique. This lets you separate the general and specific pieces of your code. Open irb and let’s explore what this separation of concerns looks like.

Suppose you have a range of numbers from 1 to 20, and you’re interested in only getting the even numbers. In Ruby, this is how you can do it:

 >>​ Array(1..20).select { |x| x.even? }
 =>​ [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

Later, you decide that the list is too big and you want to add another condition: the even numbers must also be greater than 10:

 >>​ Array(1..20).select { |x| x.even? and x > 10 }
 =>​ [12, 14, 16, 18, 20]

Notice that ...

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