Dustin Ryan-Roepsch - 11 months ago 64

Ruby Question

I'm implementing an HSV to RGB function in ruby, and I was hoping for syntax like this:

`def hsv_to_rgb(h, s, v)`

if (h == 0) then return 0, 0, 0 end

c = v * s

hp = h / 60.0

x = c * (1 - (hp % 2 - 1).abs)

r, g, b = case hp

when 0..1

c, x, 0

when 1..2

x, c, 0

when 2..3

0, c, x

when 3..4

0, x, c

when 4..5

x, 0, c

else

c, 0, x

end

m = v - c

return r + m, g + m, b + m

end

however, when I attempt to run this in Jruby I get the following error message:

SyntaxError: julia2.rb:60: syntax error, unexpected '\n'

when 1..2

Does something like this syntax exist in ruby?

Thanks!

Answer Source

Your return values in the case statement are not accepted by the ruby engine. I think you want to return an array... using the [] perhaps?

Like this:

```
def hsv_to_rgb(h, s, v)
if (h == 0) then return 0, 0, 0 end
c = v * s
hp = h / 60.0
x = c * (1 - (hp % 2 - 1).abs)
r, g, b = case hp
when 0..1
[c, x, 0]
when 1..2
[x, c, 0]
when 2..3
[0, c, x]
when 3..4
[0, x, c]
when 4..5
[x, 0, c]
else
[c, 0, x]
end
m = v - c
return r + m, g + m, b + m
end
```