better ruby algorithm