# File lib/rubygems/commands/update_command.rb, line 47
  def execute
    hig = {}

    if options[:system] then
      say "Updating RubyGems"

      unless options[:args].empty? then
        fail "No gem names are allowed with the --system option"
      end

      rubygems_update = Gem::Specification.new
      rubygems_update.name = 'rubygems-update'
      rubygems_update.version = Gem::Version.new Gem::RubyGemsVersion
      hig['rubygems-update'] = rubygems_update

      options[:user_install] = false
    else
      say "Updating installed gems"

      hig = {} # highest installed gems

      Gem.source_index.each do |name, spec|
        if hig[spec.name].nil? or hig[spec.name].version < spec.version then
          hig[spec.name] = spec
        end
      end
    end

    gems_to_update = which_to_update hig, options[:args]

    updated = []

    installer = Gem::DependencyInstaller.new options

    gems_to_update.uniq.sort.each do |name|
      next if updated.any? { |spec| spec.name == name }
      success = false

      say "Updating #{name}"
      begin
        installer.install name
        success = true
      rescue Gem::InstallError => e
        alert_error "Error installing #{name}:\n\t#{e.message}"
        success = false
      end

      installer.installed_gems.each do |spec|
        updated << spec
        say "Successfully installed #{spec.full_name}" if success
      end
    end

    if gems_to_update.include? "rubygems-update" then
      Gem.source_index.refresh!

      update_gems = Gem.source_index.find_name 'rubygems-update'

      latest_update_gem = update_gems.sort_by { |s| s.version }.last

      say "Updating RubyGems to #{latest_update_gem.version}"
      installed = do_rubygems_update latest_update_gem.version

      say "RubyGems system software updated" if installed
    else
      if updated.empty? then
        say "Nothing to update"
      else
        say "Gems updated: #{updated.map { |spec| spec.name }.join ', '}"

        if options[:generate_ri] then
          updated.each do |gem|
            Gem::DocManager.new(gem, options[:rdoc_args]).generate_ri
          end

          Gem::DocManager.update_ri_cache
        end

        if options[:generate_rdoc] then
          updated.each do |gem|
            Gem::DocManager.new(gem, options[:rdoc_args]).generate_rdoc
          end
        end
      end
    end
  end