optimize ruby solution