tags:

views:

74

answers:

1

I want to use an equivalent of Oracle's nvl() function in Ruby. Is there a built in function or do I have to write one myself?

Edit:

I am using it to rewrite some sql to ruby:

INSERT INTO my_table (id, val)
VALUES (1, nvl(my_variable,'DEFAULT'));

becomes

plsql.my_table.insert {:id => 1, :val => ???my_variable???}
+4  A: 

You could use Conditional assignment

x = find_something() #=>nil
x ||= "default"      #=>"default" : value of x will be replaced with "default", but only if x is nil or false
x ||= "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
=> nil
irb(main):003:0* x||=1
=> 1
irb(main):006:0> x=false
=> false
irb(main):008:0> x||=1
=> 1
irb(main):011:0* x||=2
=> 1
irb(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
=> nil
irb(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?) }
S.Mark
That doesn't work right if x is a non-nil false value, i.e. false.
Anonymouse
Imm, it should work for both `nil` and `false`
S.Mark
Something like `x = "default" if x.nil?` would work better
Nick Lewis