Is there a nvl() function in Ruby or do I have to write it myself? Is there a nvl() function in Ruby or do I have to write it myself? oracle oracle

Is there a nvl() function in Ruby or do I have to write it myself?


You could use Conditional assignment

x = find_something() #=>nilx ||= "default"      #=>"default" : value of x will be replaced with "default", but only if x is nil or falsex ||= "other"        #=>"default" : value of x is not replaced if it already is other than nil or false

Operator ||= is a shorthand form of the expression

x = x || "default"

Some tests

irb(main):001:0> x=nil=> nilirb(main):003:0* x||=1=> 1irb(main):006:0> x=false=> falseirb(main):008:0> x||=1=> 1irb(main):011:0* x||=2=> 1irb(main):012:0> x=> 1

And yes, If you don't want false to be match, you could use if x.nil? as Nick Lewis mentioned

irb(main):024:0> x=nil=> nilirb(main):026:0* x = 1 if x.nil?=> 1

Edit:

plsql.my_table.insert {:id => 1, :val => ???????}

would be

plsql.my_table.insert {:id => 1, :val => x || 'DEFAULT' }

where x is the variable name to set in :val, 'DEFAULT' will be insert into db, when x is nil or false

If you only want nil to 'DEFAULT', then use following way

{:id => 1, :val => ('DEFAULT' if x.nil?) }