tags:

views:

292

answers:

3

How can I get the opposite of a boolean in Ruby (I know that it is converted to 0/1) using a method inline?

say I have the given instance:

class Vote

  def return_opposite
    self.value
  end

end

Which obviously doesn't do anything, but I can't seem to find a method that is simple and short something like opposite() or the like. Does something like this exist and I'm just not looking at the right place in the docs? If one doesn't exist is there a really short ternary that would toggle it from 1 => 0 or 0 => 1?

+1  A: 

If you just want to access the opposite of the value, use ! as some people have said in the comments. If you want to actually change the value, that would be bool_value = !bool_value. Unless I've misunderstood your question. Which is quite possible.

MatrixFrog
+2  A: 

If you want to toggle boolean (that is false and true) , that would be as simple as just use ! as others has stated.

If you want to toggle between 0 and 1 , I can only think of something naive as below :)

def opposite
     op = {0=>1,1=>0}
     op[self.value]
end
pierr
For toggling between 0 and 1: op = 1 - op. Or, if you think in bits, op ^= 1
Wayne Conrad
+4  A: 

Boolean expressions are not 0 or 1 in Ruby, actually, 0 is not false

If n is Integer...pick one:

n == 0 ? 1 : 0
1 - n
[1, 0][n] # or maybe [1, 0][n & 1]
class Integer; def oh_1; self==0 ? 1:0; end; end; p [12.oh_1, 0.oh_1, 1.oh_1]
n.succ % 2

If n is TrueClass or FalseClass, it's going to be hard to beat:

!n

These examples differ in how they treat out-of-range input...

DigitalRoss
Thanks for the input on the 0 != false... It was me being an idiot and looking at a record in my db, it seems active record writes it as 0
Joseph Silvashy