If you want to do this with ruby, you should ask in the developer forum. If you are saerching for a plugin, Thomthoms Selection Toys have a tool for this... (Context menu -> select only -> groups)