Problem with defined?

D

Dirk Einecke

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
 
F

Florian Gross

Dirk said:
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
 
R

Robert Klemme

Dirk Einecke said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,146
Messages
2,570,832
Members
47,374
Latest member
anuragag27

Latest Threads

Top