From: Michael Morin Date: 2008-08-31T10:56:49+09:00 Subject: Re: Simple conditional causing hanging? Will Dresh wrote: > I have the following conditional inside a method: > > if ( @thisLine.class != 'NilClass' ) > return @thisLine.class.to_s > else > return 'nope' > end > > Obviously, all I'm trying to do is test if @thisLine is nil or not. > When I call this method later on from inside the program, at a point > when I know that @thisLine is nil, it returns 'NilClass'. This means > that my conditional has failed; it should have returned 'nope'. > > Alright, this makes sense to me. It's failing because I'm trying to > compare an object of type Class (@thisLine.class) to an object of type > String ('NilClass'). Easy fix, right? I'll just convert that Class > object to a String object before comparing... > > if ( @thisLine.class.to_s != 'NilClass' ) > return @thisLine.class.to_s > else > return 'nope' > end > > But now, when I call this method, my program hangs. I am completely > stumped as to why this happens. Any variations to this that I think > WOULD work properly, also hang. In addition to the above code, I have > also tried: > > if ( @thisLine != nil ) > if ( @thisLine.class != NilClass ) > > I would very much appreciate it if someone could explain to me why these > extremely simple method calls are apparently causing the program to > hang. > > Thanks! > -Will You want @thisLine.nil?. Alternatively, you could use @thisLine == nil, @thisLine.class == NilClass, or even @thisClass === NilClass. But @thisLine.nil? is the preferred way. -- Michael Morin Guide to Ruby http://ruby.about.com/ Become an About.com Guide: beaguide.about.com About.com is part of the New York Times Company