Ruby Moderate Interview Questions

When opening a connection to a remote service, it's typically important to make sure that the connection (or "resource") is closed - no matter what happens in the code that uses the resource. In Java this might be done as follows:

Connection conn;
try{
  conn = new Connection("some service");
  conn.doSomething();
}
catch(Exception e){}
finally{
  conn.close();
}

This pattern is tedious and repetitious, and depends on the programmer to remember to include the finally clause. In Ruby, we can do better. Suppose we wished developers to be able to safely manage connection resources using a pattern like the following...

Connection conn = new Connection("some server")
using(conn){
   conn.doSomething();
}

Define a Kernel method using that ensures that no matter what happens within the using block, the connection is always closed.

In Ruby, there are three methods for converting a block into a Proc object (see below). Discuss the differences between these three choices.

b1 = Proc.new{|x| x + 1}
b2 = lamba{|x| x + 1}
b3 = proc{|x| x + 1 }