Ruby-on-rails 是否有等同于 PHP 的 isset() 的 Rails?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5035864/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 00:27:51  来源:igfitidea点击:

Is there a Rails equivalent to PHP's isset()?

ruby-on-railsruby

提问by keybored

Basically just a check to make sure a url param was set. How I'd do it in PHP:

基本上只是检查以确保设置了 url 参数。我将如何在 PHP 中做到这一点:

if(isset($_POST['foo']) && isset($_POST['bar'])){}

Is this the rough/best equivalent to isset() in RoR?

这是 RoR 中 isset() 的粗略/最佳等价物吗?

if(!params['foo'].nil? && !params['bar'].nil?) end

回答by Simone Carletti

The closer match is probably #present?

更接近的比赛可能是 #present?

# returns true if not nil and not blank
params['foo'].present?

There are also a few other methods

还有一些其他的方法

# returns true if nil
params['foo'].nil?

# returns true if nil or empty
params['foo'].blank?

回答by Andrew

You can also use defined?

你也可以使用 defined?

See example from: http://www.tutorialspoint.com/ruby/ruby_operators.htm

请参阅以下示例:http: //www.tutorialspoint.com/ruby/ruby_operators.htm

foo = 42
defined? foo    # => "local-variable"
defined? $_     # => "global-variable"
defined? bar    # => nil (undefined)

Many more examples at the linked page.

链接页面上的更多示例。

回答by Jacob Relkin

Yes. .nil?is the equivalent of isset()in that casewhen checking the existence of a key in a Hash.

是的。.nil?相当于isset()在那种情况下检查 a 中的键是否存在Hash

You should use Hash's key?method, which returns trueif the given key is present in the receiver:

你应该使用Hash'skey?方法,true如果给定的键存在于接收器中,它会返回:

if(params.key?('foo') && params.key?('bar')) end

回答by BitOfUniverse

I think the most important thing, when you migrating from PHP to ROR, is the understanding of the fact that in Ruby everything is true except false and nil

我认为最重要的事情是,当你从 PHP 迁移到 ROR 时,要理解这样一个事实:在 Ruby 中,除了 false 和 nil 之外,一切都是真的

So, your code:

所以,你的代码:

if(!params['foo'].nil? && !params['bar'].nil?){}

if(!params['foo'].nil? && !params['bar'].nil?){}

is equivalent for:

相当于:

if(params['foo'] && params['bar']) end

if(params['foo'] && params['bar']) end

and this is full equivalent for your PHP code.

这完全等同于您的 PHP 代码。