rgb to hex conversion

The rgb() method is incomplete. Complete the method so that passing in RGB decimal values will result in a hexadecimal representation being returned. The valid decimal values for RGB are 0 - 255. Any (r,g,b) argument values that fall out of that range should be rounded to the closest valid value.

The following are examples of expected output values:

rgb(255, 255, 255) # returns FFFFFF
rgb(255, 255, 300) # returns FFFFFF
rgb(0,0,0) # returns 000000
rgb(148, 0, 211) # returns 9400D3

Answers:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
def (r, g, b)

rgb_list = [r,g,b].map {|item|
if item < 0
0
elsif item >255
255
else
item
end
}
rgb_list.inject("") {|str,item| str + item.to_s(16).rjust(2,"0")}.swapcase
end


def (r, g, b)
"%.2X%.2X%.2X" % [r,g,b].map{|i| [[i,255].min,0].max}
end

def (r, g, b)
[r, g, b].map do |c|
if c <= 0
"00"
elsif c > 255
"FF"
else
c.to_s(16).upcase
end
end.join('')
end

def (r, g, b)
[r, g, b].map{ |n| [0, n, 255].sort[1].to_s(16).upcase.rjust(2, "0")}.join
end

def (r, g, b)
[r, g, b].map do |i|
i = 0 if i < 0
i = 255 if i > 255
i.to_s(16).rjust(2, '0').upcase
end.join
end