Multiple attempts to find the best icon I have a series if statements where I am trying to find the highest resolution file in an set of files. Is there a way that I can refactor this code to be shorter and or cleaner?

begin
  icon = icons.find { |name, _| name.downcase.include? 'xxxhdpi' }
  if icon.nil?
    icon = icons.find { |name, _| name.downcase.include? 'xxhdpi' }
  end
  if icon.nil?
    icon = icons.find { |name, _| name.downcase.include? 'xhdpi' }
  end
  if icon
    File.open(tmp_icon.path.to_s, 'wb') do |f| 
      icon { |_, data| f.write data }
      s3_icon = bucket.objects[icon_path].write(Pathname.new(tmp_icon.path),
                                              content_type: 'image/png')
      icon_url = s3_icon.public_url(secure: true)
    end
  end
ensure
  tmp_icon.close
  tmp_icon.unlink
end
In order to properly give precedence to higher DPI images, you need to do three separate finds like your code already does. However, this part can be cleaned up, as well as getting rid of the unnecessary icon.try do ... end call.

begin
  icon = icons.find { |name, _| name.downcase.include? 'xxxhdpi' }
      || icons.find { |name, _| name.downcase.include? 'xxhdpi' }
      || icons.find { |name, _| name.downcase.include? 'xhdpi' }

  return unless icon.defined?

  File.open(tmp_icon.path.to_s, 'wb') { |f| f.write icon[:data] }
  s3_icon = bucket.objects[icon_path].write(Pathname.new(tmp_icon.path),
                                            content_type: 'image/png')
  icon_url = s3_icon.public_url(secure: true)
ensure
  tmp_icon.close
  tmp_icon.unlink
end