简体   繁体   中英

Using a case statement to assign multiple variable in ruby

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!

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

返回数组将起作用,并且可读性也更高。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM