how to set 2 variables to either 1 or 0 based on a 3rd variables value
I have a variable that will have the following values:
blah = # 1, 0, or -1
Now I want to set these two variables:
up
down
To either 1 or 0 based on the value of 'blah'.
If blah is 1, then up = 1 and down = 0, if blah is -1 then down = 1 and up = 0
If blah is 0, then both are 0.
How can you do this the ruby way w/o so 开发者_开发知识库many if checks?
Solution 1
up, down =
case blah
when 1; [1, 0]
when 0; [0, 0]
when -1; [0, 1]
end
Solution 2 (Inspired by mu is too short)
up, down = [[0, 0], [1, 0], [0, 1]][blah]
A variant of sawa's and SirDarius's that allows blah
to be greater than, less than, or equal to zero rather than just -1, 0, or 1:
def mapper(x)
h = {
-1 => [0, 1],
0 => [0, 0],
1 => [1, 0]
}
h[x <=> 0]
end
up, down = mapper(blah)
Note that Fixnum's <=>
operator is specified to return -1, 0, or 1 (or nil
of course):
Returns -1, 0, +1 or nil depending on whether fix is less than, equal to, or greater than numeric.
So using <=>
is a safe way to implement the signum function for Fixnum.
According to your initial specification, the following code worked:
up = 0
down = -blah
EDIT:
Here is a creative way to achieve the desired result using a Hash:
states = { -1 => [0,1], 0 => [0,0], 1 => [1,0] }
up, down = states[blah]
up = blah == 1 ? 1 : 0
down = blah == -1 ? 1 : 0
I don't think this is ruby-specific... something like
up = blah != -1
down = blah != 1
I assume you mean that up should be 1 when blah is 1.
Yet another way to do it:
up, down = [0, blah].max, [0, -blah].max
Reset both answers to 0 and then adjust as necessary
up, down = 0, 0
up = 1 if blah > 0
down = 1 if blah < 0
class Integer
def up?
self == 1
end
def down?
self == -1
end
end
x = 1
x.up? # => true
精彩评论