Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

oracle

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???}
like image 798
jva Avatar asked May 12 '10 08:05

jva


People also ask

How do I write NVL in SQL?

Another example using the NVL function in Oracle/PLSQL is: SELECT supplier_id, NVL(supplier_desc, supplier_name) FROM suppliers; This SQL statement would return the supplier_name field if the supplier_desc contained a null value. Otherwise, it would return the supplier_desc.

How does NVL function work?

The NVL function accepts two arguments: the first argument takes the name of the expression to be evaluated; the second argument specifies the value that the function returns when the first argument evaluates to NULL. If the first argument does not evaluate to NULL, the function returns the value of the first argument.

Can we use NVL in insert statement?

WHERE emp_name LIKE 'Test'), (insert into employee values((select max(emp_id)+1 from employee),'Test'))))); I mean i will check for the record to exist in the table and if not exist i will add it to the table.

What is NVL in coding?

NVL is a substitution function; that is, it is used to display one value if another value is NULL. And not just zero, but NULL, empty, void.


1 Answers

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?) }
like image 155
YOU Avatar answered Nov 04 '22 07:11

YOU