Convert RGB Color to HEX Color Ruby

I am not able to get correct hex values when I try to convert the rgb color from JSON string to the HEX code. This is my code

lane :test_code do
  update_android_strings(
    xml_path: 'app/src/main/res/values/colors.xml',
    block: lambda { |strings|
      color_json = JSON.parse(ENV['SPLASHSCREEN_COLORS'], symbolize_names: true)
      red = (color_json[:red].to_f * 255).round
      green = (color_json[:green].to_f * 255).round
      blue = (color_json[:blue].to_f * 255).round
      color_value = "#" + (red + green + blue).to_s

      puts color_value
      # string['splashColors'] = color_value
    }
  )
end

Let's get a two digit hex code for a value using sprintf.

E.g.

irb(main):003:0> color = 15
=> 15
irb(main):004:0> sprintf "%02x", color
=> "0f"
irb(main):005:0>

Then we can avoid repetition of code by mapping over an array of the color names created with %w(red green blue). We'll map each color name to its corresponding two digit hex code, then join those together and interpolate that into a string with a leading #.

lane :test_code do
  update_android_strings(
    xml_path: 'app/src/main/res/values/colors.xml',
    block: lambda { |strings|
      color_json = JSON.parse(ENV['SPLASHSCREEN_COLORS'], symbolize_names: true)
      colors = %w(red green blue)
      codes = colors.map { |c| sprintf "%02x", color_json[c].to_i }
      puts "##{codes.join}"
    }
  )
end

Or we could simply map to the integers, and then expand that array out into the args to sprintf, like so:

lane :test_code do
  update_android_strings(
    xml_path: 'app/src/main/res/values/colors.xml',
    block: lambda { |strings|
      color_json = JSON.parse(ENV['SPLASHSCREEN_COLORS'], symbolize_names: true)
      colors = %w(red green blue)
      puts sprintf("#%02x%02x%02x", *colors.map { |c| color_json[c].to_i })
    }
  )
end

You can try it this way:

  red = color_json[:red].to_i.to_s(16)
  green = color_json[:green].to_i.to_s(16)
  blue = color_json[:blue].to_i.to_s(16)
  color_value = sprintf("#%02x%02x%02x", r, g, b)