Is there a Rails equivalent to PHP's isset()?
Basically just a check to make sure a url param was set. How I'd do it in PHP:
if(isset($_POST['foo']) && isset($_POST['bar'])){}
开发者_如何转开发
Is this the rough/best equivalent to isset() in RoR?
if(!params['foo'].nil? && !params['bar'].nil?) end
The closer match is probably #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?
You can also use defined?
See example from: 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.
Yes. .nil?
is the equivalent of isset()
in that case when checking the existence of a key in a Hash
.
You should use Hash
's key?
method, which returns true
if the given key is present in the receiver:
if(params.key?('foo') && params.key?('bar')) end
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
So, your code:
if(!params['foo'].nil? && !params['bar'].nil?){}
is equivalent for:
if(params['foo'] && params['bar']) end
and this is full equivalent for your PHP code.
精彩评论