On Apr 3, 2007, at 8:39 PM, Jamal Soueidan wrote:

> From my previous language (PHP) I could easily write function like  
> this
>
> if (empty($var))
>
> even if the $var is not declared..
>
> I thought in Ruby it will work the same way

Ruby does not have an analogous concept to PHP's empty.

Ruby's 'defined?' is closer to PHP's 'isset' (for variables) or
'defined' (for constants).

You have to be careful with analogies between PHP and Ruby because
the languages don't treat variables, data and objects in the same
way at all.  For example, PHP's function 'is_object(var)' is
superfluous in Ruby since if a variable is defined it must refer
to an object--there are no other 'things' that a variable can
reference.  In PHP a basic string is *not* an object.  Ruby does
not have that type of distinction.

The various tests for Ruby objects that would match PHP's empty
function:

         "".empty?      # true for an empty string
         "x".empty?     # false
         "0".empty?     # false (strings aren't auto converted )
         "0".to_int.zero? # true

         0.zero?        # true
         1.zero?        # false

         nil.nil?       # yes, nil is the nil object
         0.nil?         # no, zero is not nil object

         x = false      # make x refer to the false object
         x == false     # true, x refers to the false object
         x == true      # false, x doesn't refer to the false object
         x = true       # x now refers to the false object
         x == false     # false, x doesn't refer to the false object
         x == true      # true, x does refer to the false object

         [].empty?      # true, the array is empty
         [100].empty?   # false, the array is not empty

In a boolean context false and nil are the only objects that are
considered false.  All other objects (0, an empty array, an empty
string) are considered true:

if x
   # x is neither nil nor false
else
   # x must be nil or false
end

If you really wanted to match PHP's empty function you would have to do
something like:

def empty(obj)
   [nil, 0, false, [], "", "0"].include?(obj)
end

But that still won't work for variables that are not defined.  In
practice the need to decide if a variable is defined or not is rare
though.

> so in Ruby everything is object if it was declared before :P o

As with most absolutes the phrase 'everything is an object' is only
true within a particular context.  In this case with respect to
data.  All data in Ruby is accessed and manipulated in the context
of objects and their methods.  But variables are not data in Ruby.
Variables reference objects but aren't themselves objects.  Other
parts of the language can be accessed and manipulated as objects
(data) though:  classes, modules, methods, and more.


Gary Wright