Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting `false` into `nil`

Tags:

null

ruby

When you want to convert a varible v into false when it is nil/false and true otherwise, there is an easy way to do it:

!!v

But is there an easy way to convert v into nil when it is nil/false and retain its value otherwise?

like image 332
sawa Avatar asked Dec 15 '11 06:12

sawa


1 Answers

You can use ||=:

a = 'hello'
a ||= nil #=> "hello"

a = true
a ||= nil #=> true

a = false
a ||= nil #=> nil

a = nil
a ||= nil #=> nil
like image 64
Mischa Avatar answered Oct 30 '22 17:10

Mischa