Ruby中是否有nvl()函数,还是我必须自己编写? [英] Is there a nvl() function in Ruby or do I have to write it myself?

查看:101
本文介绍了Ruby中是否有nvl()函数,还是我必须自己编写?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Ruby中使用等效于Oracle的nvl()函数.是否有内置函数或我必须自己编写一个函数?

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?

我正在使用它将一些sql重写为ruby:

I am using it to rewrite some sql to ruby:

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

成为

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

推荐答案

您可以使用有条件的分配

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"

一些测试

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

是的,如果您不希望匹配假,则可以使用Nick Lewis提到的if x.nil?

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

修改:

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

将是

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

其中x是在:val中设置的变量名,当x为nil或false时,'DEFAULT'将插入db

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

如果您只想将nil设为'DEFAULT',请使用以下方式

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

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

这篇关于Ruby中是否有nvl()函数,还是我必须自己编写?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆