Transliteration of js solution into ruby