Consider some of the things you would use for anonymous classes in Java. for example, they are often used for plug-in behavior, such as event listeners, or for parameterizing a method that has a common layout.
Imagine that we want to write a method that accepts a list and returns a new list containing elements from the given list for which the specified condition is true. In Java, we will write an interface:
interface Condition { boolean f(Object o); }
and then we could write:
public List select(List list, Condition c) { List result = new ArrayList(); for (Object item : list) { if (cf(item)) { result.add(item); } } return result; }
and then if we want to select even numbers from the list, we could write:
List even = select(mylist, new Condition() { public boolean f(Object o) { return ((Integer) o) % 2 == 0; } });
To write the equivalent in Ruby, it could be:
def select(list) new_list = []
and then we could choose even numbers with just
even = select(list) { |i| i % 2 == 0 }
Of course, this functionality is already built into Ruby, so in practice you just do
even = list.select { |i| i % 2 == 0 }
As another example, consider the code to open a file. You can do:
f = open(somefile)
but then you need to think about putting your close in the ensure block in case of an exception while working with the file. Instead you can do
open(somefile) do |f|