0

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 

3 Answers 3

2

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) 
Sign up to request clarification or add additional context in comments.

2 Comments

Be careful. If color_json[:red] is "15", the result would be "f" which just gets directly put into the final string. You may want to just convert these values to ints, then use something like sprintf("#%02x%02x%02x", r, g, b).
Regarding your edit: you have to remove the to_s(16) conversion when using %02x.
1

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 

Comments

0

This should work quite nicely.

color_json = JSON.parse(ENV['SPLASHSCREEN_COLORS'], symbolize_names: true) color_value = '#' + %i[red green blue].map { |c| color_json[c].to_i.to_s(16).rjust(2, '0') }.join puts color_value 

String#rjust lets you add padding to a string to make sure its length is always greater than or equal to the specified number.

"1".rjust(3, '-') #=> "--1" "21".rjust(3, '-') #=> "-21" "321".rjust(3, '-') #=> "321" "4321".rjust(3, '-') #=> "4321" 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.