Ruby optimizations and bugfixes

See commit messages for details.