Problem with defined?

Hi.

I've a class to get all vars from params:

class CgiParamsToLocal
   def initialize(params)
     @params = params
   end
   def method_missing(m, *other)
     @params[m.to_s][0]
   end
end

Using:

p = CgiParamsToLocal.new($cgi.params)

No I want to check if for example p.foo ist defined. I tried it like this:

print p.foo # -> Test
if ( defined?(p.foo) ) then
   # do something
else
   # do some other things
end

Well - p.foo is defined but why I ever get only the else part?

If I do it like this all is okay:

print p.foo # -> Test
if ( p.foo.length != 0 ) then
   # do something
else
   # do some other things
end

Now - why is defined? not working in my example?

greetings
Dirk Einecke

Dirk Einecke wrote:

Hi.

Moin!

Now - why is defined? not working in my example?

defined?() is very magical and doesn't check the return value of the method call, but rather if the method itself exists at all.

Your example seems not to be working correctly -- I think that CgiParamsToLocal will raise an Exception when the element doesn't exist. (You're accessing @params[m.to_s][0], but @params[m.to_s] could be nil)

If I were you I would just return nil from method_missing and then do puts "p.foo" if p.foo or something similar in your actual code.

greetings
Dirk Einecke

Regards,
Florian Gross

"Dirk Einecke" <dirk.einecke@gmx.de> schrieb im Newsbeitrag
news:2lt74lFgkgt1U1@uni-berlin.de...

Hi.

I've a class to get all vars from params:

class CgiParamsToLocal
   def initialize(params)
     @params = params
   end
   def method_missing(m, *other)
     @params[m.to_s][0]
   end
end

Using:

p = CgiParamsToLocal.new($cgi.params)

No I want to check if for example p.foo ist defined. I tried it like this:

print p.foo # -> Test
if ( defined?(p.foo) ) then
   # do something
else
   # do some other things
end

Well - p.foo is defined but why I ever get only the else part?

Where is that defined? You don't have a method #foo in CgiParamsToLocal and
you don't create it when the instance is created. You have to invoke #foo
(the method that is missing) in order to get the value from #method_missing
back.

If I do it like this all is okay:

print p.foo # -> Test
if ( p.foo.length != 0 ) then
   # do something
else
   # do some other things
end

Now - why is defined? not working in my example?

Usually people coming grom Perl use defined? the wrong way. You typically
want "something.nil?" or just "something":

if p.foo
  # foo set
else
  # foo unset
end

or

if p.foo.nil?
  # unset
else
  # set
end

Does that help?

Regards

    robert