Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby true, false, or nil

I have an object with a boolean var.

 field :processing, :type => Boolean

The dev before me wrote some code that says this.

 :processing => nil 

(He is, for some reason, setting it to nil instead of false.)

He then does this if statement

 return if self.processing
 dosomethingelse....

If I write code that does this

:processing => false 

what happens the next time this code runs? Does dosomethingelse run?

return if self.processing
dosomethingelse....

UPDATE ===========

To many questions below so will answer here.

I added this

  field :processing, :type => Boolean, :default => false

and it broke the app. When I changed to the above dosomethingelse never gets run?
return if self.processing returns. Any suggestions?

UPDATE 2 =======================================

Here is every reference to processing in my code (redacted). Also I am using MongoDB if that matters.

.where(:processing => nil).gt(:retries => 0).asc(:send_time).all.entries


if self.processing 
end


return if self.processing
self.update_attributes(:processing => true)
dosomethingelse....


.where(:sent_time => nil).where(:processing => nil).gt(:retries => 0).asc(:send_time).all.entries

:processing => nil
like image 971
jdog Avatar asked Jan 04 '16 15:01

jdog


People also ask

Is nil a value in Ruby?

In Ruby, nil is a special value that denotes the absence of any value. Nil is an object of NilClass. nil is Ruby's way of referring to nothing or void.

How can you tell if a Ruby is real or false?

in a boolean context (if, &&, ||, etc.). Ruby has to decide whether these values count as true or false. If the value isn't literally "true" but evaluates as true, we call it "truthy." Likewise, if the value isn't literally "false" but evaluates as false, we call it "falsey."

Is nil a Boolean value?

nil is certainly not a boolean, it is it's own special value that is used to represent null values. For example instance variables (e.g. @foo ) will by default evaluate to nil if they have not previously been set.


1 Answers

Ruby uses truthy and falsey.

false and nil are falsey, everything else is truthy.

if true
  puts "true is truthy, duh!"
else
  puts "true is falsey, wtf!"
end

Output is "true is truthy, duh!"

if nil
  puts "nil is truthy"
else
  puts "nil is falsey"
end

Output is "nil is falsey"

if 0
  puts "0 is truthy"
else
  puts "0 is falsey"
end

Output is "0 is truthy"

See this explanation True and False

like image 125
Nermin Avatar answered Sep 19 '22 09:09

Nermin