Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 
like image 609
keybored Avatar asked Feb 17 '11 23:02

keybored


People also ask

What can I use instead of isset?

The equivalent of isset($var) for a function return value is func() === null .

What is isset ($_ GET?

The isset() function checks whether a variable is set, which means that it has to be declared and is not NULL. This function returns true if the variable exists and is not NULL, otherwise it returns false.

Why isset () is required explain with example when we need to use Isset?

The isset() function is a built-in function of PHP, which is used to determine that a variable is set or not. If a variable is considered set, means the variable is declared and has a different value from the NULL. In short, it checks that the variable is declared and not null.

Should I use isset?

isset() is best for radios/checkboxes. Use empty() for strings/integer inputs. when a variable contains a value, using isset() will always be true. you set the variable yourself, so it's not a problem.


2 Answers

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? 
like image 98
Simone Carletti Avatar answered Sep 22 '22 06:09

Simone Carletti


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.

like image 33
Andrew Avatar answered Sep 24 '22 06:09

Andrew