SitePoint Sponsor

User Tag List

Results 1 to 4 of 4

Hybrid View

  1. #1
    SitePoint Enthusiast selfmindead's Avatar
    Join Date
    Nov 2004
    Location
    Las Vegas, NV
    Posts
    28
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    checking to see if a variable is set..

    Hey guys, i have a pretty quick question. I need to make an IF statement that does #action if a certain param (params[:theme]) is set.

    How would i go about coding that with ruby? As an example I'll include the PHP equivilent of what i need to do...

    Code:
    <?php
     if (isset($_GET['id'])){
        # Do some code here, id had a value.
      }else{
        # Do some code here, id did NOT have a value.
      }
     ?>
    OR

    Code:
    <?php
     if (empty($_GET['id'])){
        # Do some code here, id did NOT have a value.
      }else{
       # Do some code here, id had a value.
      }
     ?>
    Thanks,
    - Jeremy

  2. #2
    SitePoint Zealot
    Join Date
    Nov 2004
    Location
    Yakima WA.
    Posts
    100
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Code:
    if params[:foo]
       # do something with params[:foo]
    else
       # do something else because params[:foo] is empty.
    end
    -Ezra

  3. #3
    SitePoint Evangelist
    Join Date
    Jun 2004
    Location
    California
    Posts
    440
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I use the Object#nil? method.
    Code:
    if params[:foo].nil? then
    ...
    end
    And #empty?

  4. #4
    SitePoint Wizard stereofrog's Avatar
    Join Date
    Apr 2004
    Location
    germany
    Posts
    4,324
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Undefined hash offsets have a value of nil (unlike php, you don't get any error message when accessing undefined offset).

    if !params[:foo] means "params[:foo] is not set or it is equal to false"
    if params[:foo].nil? means "params[:foo] is not set"

    empty() function is quite silly and I'd avoid it even in php. In ruby there is absolutely no need of it. 0 (zero) and "" (empty string) are ordinary values like any other, if you want to test if a var == 0, compare it to 0.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •