Completed translating PHP to Ruby script