You can use the select method of an array to grab matching keys, something like:

      matching_keys = posixaccount.sshpublickey.select { |key| key.slice(/^ssh-[^ ]+ [^ ]+/) == key_portion }
      unless matching_keys.size > 0
        # add the key here
      end